BayesianOptimization#

class nextnano_optimizers.optimizer.BayesianOptimization(nextnanoio: IO, metric: Metric, bounds, output_dir: str | None = None)#

Bases: PlottingFacadeMixin

Optimize the device design using Bayesian optimization.

Uses the BoTorch library to optimize the objective defined by metric, evaluating candidates through nextnano simulations.

Parameters:
nextnanoioIO

Defines the input file path, input variables under optimization and output files of the simulations.

metricMetric

Defines how the objective value is extracted from the simulation outputs.

boundstuple of list

Lower and upper bounds for the optimization variables, respectively. Each list must contain one value per optimization variable, in the same order as variable_names in nextnanoio.

output_dirstr, default=None

Directory where optimization results are saved. If None, defaults to the outputdirectory specified in nextnanopy config.

Attributes:
champion_xnumpy.ndarray or None

Input variable values of the best candidate evaluated during optimization.

champion_ffloat or None

Objective value corresponding to champion_x.

Raises:
ValueError

If bounds is invalid.

See also

IO

Configure simulation inputs and outputs.

Metric

Define how objective values are calculated.

Examples

Optimize the quantum well width to match the target transition energy using Bayesian optimization.

import numpy as np
from nextnano_optimizers.io import IO
from nextnano_optimizers.metric import Metric
from nextnano_optimizers.optimizer import BayesianOptimization

io = IO(
    input_file_path="device.nnp",
    variable_names=["well_width"],
    output_files=["bias_00000/Quantum/energy_spectrum.dat"],
)

def extract_target(datafiles):
    energies = datafiles[0].variables["Energy"].value
    transition_energy = energies[1] - energies[0]
    return np.array([(transition_energy - 0.25) ** 2])

metric = Metric(
    input_shape=(1,),
    num_obj=1,
    extraction_function=extract_target,
)

optimizer = BayesianOptimization(
    nextnanoio=io,
    metric=metric,
    bounds=([2.0], [12.0]),
)
result = optimizer.run(trials=20)

print(result["champion_x"])  # Optimized well width
print(result["champion_f"])  # Objective value
plot_all(save_dir=None, show=False, fig_format='png')#

Plot the optimization results.

Generates figures showing the optimization progress and available visualizations of the optimization results. The figures produced depend on the number of optimization variables and objectives:

  • Optimization progress: Objective and parameter values as a function of optimization iterations.

  • Parameter space: Evaluated candidates in the design space. Plotted only for problems with multiple parameters.

  • Pareto front: The Pareto-set (the optimal set in the input space) and the Pareto front (the optimal set in the objective space). Plotted only for multi-objective problems.

Parameters:
save_dirstr or bool, default=None

Path to a directory where figures are saved. If None, figures are saved in the figures subdirectory of the optimization output directory. If False, figures are not saved. A directory is created if specified path it does not exist.

showbool, default=False

If True, display the figures.

fig_formatstr, default=”png”

File format for saving figures, such as "png", "pdf", or "svg". Ignored if save_dir=False.

Returns:
list of matplotlib.figure.Figure

Generated figures.

Raises:
RuntimeError

If called before run().

ValueError

If fig_format is not supported by matplotlib.

See also

setup_plotting

Customize the figures generated by this method. Should be called before plot_all.

Examples

Save the figures in the figures subdirectory of this run’s output directory:

>>> optimizer.run(x0=[10.0])
>>> figures = optimizer.plot_all()

Display the figures without saving them:

>>> optimizer.plot_all(save_dir=False, show=True)

Save them as PDFs in a custom directory:

>>> optimizer.plot_all(save_dir="my_figures", fig_format="pdf")

Label the axes before plotting:

>>> optimizer.setup_plotting(param_names=["well width (nm)"])
>>> optimizer.plot_all()
run(trials: int = 20, n_initial: int = 5, seed: int | None = None, non_execution_penalty=None, target: float | None = None, verbose: bool = True, live_progress: bool = False, acquisition: str = 'LogEI', acquisition_kwargs: dict | None = None) → dict#

Run the Bayesian optimization.

Progress is reported as one concise line per trial when verbose is true.

Parameters:
trialsint, default=20

Number of optimization trials to perform.

n_initialint, default=5

Trials spent on the quasi-random initial design before the surrogate model and acquisition function take over. Clipped to trials, i.e. if n_initial > trials, effectively n_intial = trials is used.

seedint, default=None

Random seed used by the Bayesian optimization algorithm.

non_execution_penaltynumbers.Number, default=None

Objective value assigned to candidates whose simulations fail. When None, such an evaluation raises RuntimeError.

targetfloat, default=None

Target objective value. The optimization stops when an evaluated objective value is less than or equal to target. If None, no target-based stopping criterion is applied.

verbosebool, default=True

If True, print optimization progress to the console.

live_progressbool, default=False

If True, display a live plot of the optimization progress. The plot updates during optimization and closes when the run finishes. To customize the plot, see setup_plotting().

acquisition{“LogEI”, “UCB”}, default=”LogEI”

Acquisition function choice.

acquisition_kwargsdict, default=None

Keyword arguments for acquisition.

Returns
——-
dict

Optimization result containing:

  • champion_x : Input variable values of the best evaluated candidate.

  • champion_f : Corresponding objective value.

Raises:
ValueError

If trials or n_initial is less than 1 or is not an integer.

RuntimeError

If a simulation fails or produces a non-finite objective value while non_execution_penalty is None.

Examples

Run the optimization for 50 trials:

>>> result = optimizer.run(trials=50)

Use 10 trial for the initialization:

>>> result = optimizer.run(trials=50, n_initial=10)

Set a random seed for reproducibility:

>>> result = optimizer.run(trials=50, seed=42)

Search with the upper-confidence-bound acquisition and a custom beta:

>>> result = optimizer.run(trials=50, acquisition="UCB")
>>> result = optimizer.run(trials=50, acquisition="UCB", acquisition_kwargs={"beta": 4.0})

Display the optimization progress:

>>> result = optimizer.run(trials=50, live_progress=True)
setup_plotting(**plotter_kwargs) → None#

Configure the optimization plots.

The configuration applies to both the live progress plot displayed by run(live_progress=True) and the figures generated by plot_all().

Parameters:
**plotter_kwargs

Plotting options described below.

param_nameslist of str, optional

Labels for the optimization variables.

objective_nameslist of str, optional

Labels for the objectives.

exclude_failedbool, optional

If True, exclude evaluations assigned the non_execution_penalty from the plots (i.e. failed evaluations).

objective_limitslist or dict, optional

Plotting limits for each objective, specified as (min, max) pairs. If dictionary is used, the keys should match the objective names, see examples below.

objective_log_scalebool or list of bool or dict, optional

Which objectives use logarithmic axis. True applies to every objective, a list gives one flag per objective. If dictionary is used, the keys should match the objective names. Objectives left out use a linear axis. Values that are zero or negative cannot be drawn on a logarithmic axis and are left out of that objective’s panel, with a warning naming it.

progress_seriesstr or sequence of str, optional

Curves to display in the optimization progress plot. Use "all" to display all available curves. The series applicable to all optimizations: (“best”, “candidates”). The series also applicable to evolution: (“min-max”, “min”, “max”, “median”, “mean”).

series_labelsdict, optional

Custom legend labels for progress_series curves, keyed by curve tag from the progress_series.

series_specsdict, optional

Custom plotting properties for individual curves, keyed by curve name. Each entry can specify kind and/or style. See examples below.

iteration_labelstr, optional

Label used for optimization iterations. Each optimizer defaults to its own word: "generation" for Evolution, "trial" for BayesianOptimization, and "evaluation" for LocalOptimizer.

progress_titlestr, optional

Title of the optimization progress plot.

population_labelstr, optional

Label used for candidates in the final iteration.

Raises:
TypeError

If an unrecognized plotting option is provided.

ValueError

In either of two cases:

  • progress_series contains an unknown curve.

  • The number of entries in param_names or objective_names does not match the number of optimization variables or objectives.

See also

plot_all

Generate figures using the configured plotting options.

Examples

Customize the labels and title of the optimization plots:

optimizer.setup_plotting(
    param_names=["Well width (nm)", "Barrier width (nm)"],
    objective_names=["Energy error (eV)"],
    progress_title="Quantum well optimization",
)

optimizer.plot_all()

Customize the progress curves and objective limits for an Evolution optimizer. Plot only the candidates with “Energy error” and “Efficiency” within specified ranges. Change the style of the “best” and “mean” lines.

optimizer.setup_plotting(
    objective_names=["Energy error", "Efficiency"],
    objective_limits={
        "Energy error": (0, 0.5),
        "Efficiency": (0, 1),
    },
    progress_series=["best", "mean", "min-max"],
    series_specs={
        "best": {"kind": "line", "style": {"linewidth": 2}},
        "mean": {"kind": "line", "style": {"linestyle": "--"}},
    },
)

optimizer.plot_all()