LocalOptimizer#
- class nextnano_optimizers.optimizer.LocalOptimizer(nextnanoio: IO, metric: Metric, output_dir: str | None = None)#
Bases:
PlottingFacadeMixinMinimize a scalar objective using local optimization algorithms.
Uses
scipy.optimize.minimizeto optimize the objective defined bymetric, evaluating candidates through nextnano simulations. The optimization starts from an initial guess and searches for a local minimum.- 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.
- output_dirstr, default=None
Directory where optimization results are saved. If
None, defaults to theoutputdirectoryspecified in nextnanopy config.
- Attributes:
- champion_xnumpy.ndarray or None
Input variables of the best candidate evaluated during optimization.
- champion_ffloat or None
The objective value of the best candidate evaluated during optimization.
See also
IOConfigure simulation inputs and outputs.
MetricDefine how objective values are calculated.
scipy.optimize.minimize()SciPy function used for local optimization.
Examples
Optimize the quantum well width to match the target transition energy.
import numpy as np from nextnano_optimizers.io import IO from nextnano_optimizers.metric import Metric from nextnano_optimizers.optimizer import LocalOptimizer 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 = LocalOptimizer(nextnanoio=io, metric=metric) result = optimizer.run(x0=[6.0], method="Nelder-Mead") print(result.x) # Optimized well width print(result.fun) # objective value at optimizerd well width
- 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
matplotlibdependency (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 thefiguressubdirectory of the optimization output directory. IfFalse, 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 ifsave_dir=False.
- Returns:
- list of matplotlib.figure.Figure
Generated figures.
- Raises:
- RuntimeError
If called before
run().- ValueError
If
fig_formatis not supported by matplotlib.
See also
setup_plottingCustomize the figures generated by this method. Should be called before
plot_all.
Examples
Save the figures in the
figuressubdirectory 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(x0, *, live_progress: bool = False, **kwargs)#
Run the optimization.
- Parameters:
- x0float or array-like
Initial values of the optimization variables, in the same order as
variable_namesinnextnanoio. A scalar is acceptable when optimizing a single variable.- 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 optionalmatplotlibdependency. For the progress plot customization, seesetup_plotting().- **kwargs
Additional keyword arguments passed to
scipy.optimize.minimize, such asmethod,bounds,options. Seescipy.optimize.minimize()for the full list.
- Returns:
- scipy.optimize.OptimizeResult
The result returned by
scipy.optimize.minimize().
- Raises:
- ValueError
If the metric is multi-objective, or if
x0does not have one entry per input variable.- RuntimeError
If nextnano simulation fails to run (syntax error, convergence failure etc).
Notes
champion_xhold the best candidate found during the run. That is normally the same point reported inOptimizeResult.x, but not always. The exact behavior depends on the optimization algorithm. For example, an algorithm may evaluate the best point found during the search, later move away from it, and eventually converge to a different local minimum.
- 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 byplot_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 thenon_execution_penaltyfrom 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
kindand/orstyle. See examples below.- iteration_labelstr, optional
Label used for optimization iterations. Each optimizer defaults to its own word:
"generation"forEvolution,"trial"forBayesianOptimization, and"evaluation"forLocalOptimizer.- 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_seriescontains an unknown curve.The number of entries in
param_namesorfitness_namesdoes not match the number of optimization variables or objectives.
See also
plot_allGenerate 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
Evolutionoptimizer. 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()