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 Ax library to optimize the objective defined by metric, evaluating candidates through nextnano simulations. Requires the optional ax dependency (pip install nextnano_optimizers[bayesian]).

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.

ax_clientax.Client or None

The Ax client from the last run, kept for post-run inspection (e.g. ax_client.summarize() returns a per-trial pandas.DataFrame). None before run.

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"],
    target_output_paths=[("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,),
    output_shape=(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:

Requires the optional matplotlib dependency (pip install nextnano_optimizers[plot]).

  • 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, seed: int | None = None, non_execution_penalty=None, target: float | None = None, verbose: bool = True, live_progress: bool = False) → dict#

Run the Bayesian optimization.

Ax’s own per-trial logging is quieted for the duration; progress is reported as one concise line per trial when verbose is true.

Parameters:
trialsint, default=20

Number of optimization trials to perform.

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. Requires the optional matplotlib dependency. To customize the plot, see setup_plotting().

Returns:
dict

Optimization result containing:

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

  • champion_f : Corresponding objective value.

  • client : Ax client containing the optimization history.

Raises:
ValueError

If trials 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)

Set a random seed for reproducibility:

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

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.

fitness_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).

fitness_limitslist or dict, optional

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

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 fitness_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)"],
    fitness_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(
    fitness_names=["Energy error", "Efficiency"],
    fitness_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()