Metric#
- class nextnano_optimizers.metric.Metric(input_shape: tuple[int, ...], num_obj: int, extraction_function: Callable | None = None)#
Bases:
objectDefines how simulation output datafiles are converted into numerical objective values using a user-defined extraction function.
Supports both single-objective and multi-objective optimization.
- Parameters:
- input_shapetuple of int
Shape of the array of
nextnanopy.DataFileobjects passed to the extraction function:(k,)without sweep or(k, n1, n2, ...)with sweep, wherekis the number of target output files andn1,n2, etc. are the sweep dimensions.- num_objint
Number of objectives. The extraction function must return a
numpy.ndarrayof shape(num_obj,):1for single-objective optimization, more for multi-objective optimization.- extraction_functioncallable, default=None
User-defined function
f(dfiles) -> numpy.ndarraythat converts the array of DataFile objects into a one-dimensional array of objective values. If None,default_extractoris used.
- Attributes:
- input_shapetuple of int
Shape of the array of
nextnanopy.DataFileobjects passed to the extraction function.- num_objint
Number of objectives returned by the extraction function.
- extraction_functioncallable
Function converting the array of DataFile objects into objective values.
Examples
Without sweep
Define an extraction function that calculates the confinement energy of the first excited state:
>>> import numpy as np >>> def extract_confinement_energy(datafiles): ... band_edge = datafiles[0].variables["Gamma"].value ... energies = datafiles[1].variables["Energy"].value ... return np.array([band_edge.max() - energies[1]])
>>> metric = Metric( ... input_shape=(2,), ... num_obj=1, ... extraction_function=extract_confinement_energy, ... )
With sweep
For an
IOinstance configured withsweep={"temperature": [200, 300, 400]}, calculate the average confinement energy across the three temperatures:>>> def extract_average_confinement(datafiles): ... confinement = [] ... for i in range(3): ... band_edge = datafiles[0, i].variables["Gamma"].value ... energies = datafiles[1, i].variables["Energy"].value ... confinement.append(band_edge.max() - energies[1]) ... return np.array([np.mean(confinement)])
>>> metric = Metric( ... input_shape=(2, 3), ... num_obj=1, ... extraction_function=extract_average_confinement, ... )
- extract(input_datafiles, *args, **kwargs)#
Computes the metric array from the input datafiles.
- Parameters:
- input_datafilesnumpy.ndarray or list
ndarray of shape
input_shape(object dtype, elements are DataFiles), or a plain list for backward-compatible 1D-input callers.
- Returns:
- numpy.ndarray
Array of shape
(num_obj,)returned by the extraction function.
- Raises:
- ValueError
If input_datafiles’ shape (or length, for a plain list) does not match input_shape, or if the extraction function’s result shape is not
(num_obj,).- TypeError
If the extraction function does not return a numpy.ndarray.