Python API reference¶
The public classes are available from the top-level openmc_optimizer
package:
from openmc_optimizer import (
MaterialFraction,
OpenMCOptimizer,
OptimizationResult,
VolumeFraction,
)
OpenMCOptimizer¶
Create an optimizer by passing the model directory and one or more design
variables to OpenMCOptimizer. All arguments are keyword-only:
OpenMCOptimizer(
*,
model_dir,
variables,
method="genetic",
assembly_cell_ids=None,
ppf_tally_name=None,
ppf_tally_score="fission-q-recoverable",
target_ppf=None,
target_keff=None,
keff_tolerance=0.005,
ppf_weight=0.7,
keff_weight=0.3,
ppf_scale=0.5,
population_reduction_rate=0.20,
work_dir="results",
population_size=20,
generations=30,
elite_count=2,
mutation_rate=0.15,
mutation_scale=0.12,
surrogate_evaluation_fraction=0.5,
seed=1,
openmc_command=("openmc",),
statepoint_file="statepoint.100.h5",
)
Arguments¶
methodSearch method:
"genetic"(default) or"bayesian". Bayesian optimization uses a Gaussian-process surrogate. Scikit-learn is installed as a required project dependency.model_dirRequired path to the directory containing the OpenMC XML model. It must contain at least
geometry.xml,materials.xml, andsettings.xml. Relative paths are resolved from the current working directory.variablesRequired non-empty list of
MaterialFractionand/orVolumeFractioninstances. Each variable’snamemust be unique. When omitted, a variable’s name is constructed from its component, basis, and material ID (or from the target and component IDs for volume mixing).assembly_cell_idsOptional list or tuple of positive geometry cell IDs for assembly root cells. If omitted, the optimizer attempts to infer suitable cells from the nested lattice structure. Supply IDs explicitly if inference does not match the assemblies used by the model.
ppf_tally_nameOptional name of a user-defined tally already present in
tallies.xml. When provided, the optimizer uses this tally instead of creating its built-in assembly power tally. The tally must have exactly one spatial filter, one total nuclide bin, and one value per region for the selected score. Supported filters are cell, cell-instance, distribcell, material, mesh, and universe. Those bins must represent integrated, power-proportional values over the regions whose peaking factor you want to minimize. The optimizer calculates \(\max(P_i)/\operatorname{mean}(P_i)\) over the returned values. It cannot infer whether arbitrary tally bins represent comparable regions or a power measure, so that compatibility is the user’s responsibility. If omitted, the built-in assembly tally is used andassembly_cell_idscontrols its regions.ppf_tally_scoreScore read from the selected PPF tally. Defaults to
"fission-q-recoverable". The score must be power-proportional and must be present in the user tally whenppf_tally_nameis set.target_ppfOptional positive PPF threshold. The selected method stops early when its best candidate meets this PPF threshold and, if configured, the keff target tolerance.
target_keffOptional positive effective multiplication factor target. Candidates within
keff_toleranceare considered feasible; among feasible candidates the optimizer minimizes the weighted loss. Both methods prioritize candidates closer to the target while no feasible candidate has been found.keff_toleranceAbsolute tolerance around
target_keff. Defaults to0.005. A candidate is feasible when \(|k_{\mathrm{eff}}-k_{\mathrm{target}}|\le\tau_k\). This setting is ignored whentarget_keffisNone.ppf_weightandkeff_weightNon-negative weights for the PPF and keff terms in the loss. The weights are normalized by their sum. Defaults to
0.7for PPF and0.3for keff. They affect ranking only after the candidate meets the keff tolerance. Iftarget_keffisNone, only the PPF objective is active andppf_weightmust be positive.ppf_scalePositive normalization scale for PPF excess above 1. Defaults to
0.5. The normalized PPF term is \(\max(\mathrm{PPF}-1,0)/s_{\mathrm{PPF}}\); the normalized keff term is \(|k_{\mathrm{eff}}-k_{\mathrm{target}}|/\tau_k\).work_dirDirectory for candidate runs and optimization outputs. Defaults to
resultsrelative to the current working directory.population_sizeFor the genetic method, number of candidates in the first generation. For Bayesian optimization, number of samples in the initial Latin-hypercube design. Must be at least 10.
population_reduction_rateGenetic algorithm only. Fraction by which each generation’s population is reduced. Defaults to
0.20(20%). Must be in[0, 1). Set to0to keep the population size constant; the minimum population size remains 10.generationsFor the genetic method, maximum number of generations. For Bayesian optimization, maximum number of sequential surrogate-guided evaluations after the initial design. Must be at least 1.
elite_countGenetic algorithm only. Maximum number of top candidates copied unchanged to the next generation. Must be at least 1 and less than the initial
population_size. As the population shrinks, the elite count is capped to leave at least one slot for a new child.mutation_rateGenetic algorithm only. Probability that each child parameter is mutated independently. Must be between 0 and 1 inclusive.
mutation_scaleGenetic algorithm only. Standard deviation of a mutation as a fraction of that parameter’s bounds range. Must be non-negative. A value of 0 disables mutation changes even when a parameter is selected for mutation.
surrogate_evaluation_fractionGenetic algorithm only. Fraction of the reduced population used as the evaluation budget for surrogate-screened offspring in each later generation. Defaults to
0.5and must be in(0, 1]. The initial population is always evaluated in full. A value of1.0evaluates all selected offspring; smaller values reduce OpenMC runs but rely more on the surrogate’s ranking. At least two proposals are evaluated per later generation when available.seedInteger seed for the selected method’s random choices. It does not remove OpenMC Monte Carlo uncertainty.
openmc_commandCommand used to run OpenMC in each candidate directory. Provide a sequence such as
("openmc",)or("mpirun", "-n", "8", "openmc").statepoint_fileName of the statepoint file OpenMC is expected to produce. Defaults to
statepoint.100.h5.
Methods¶
run()Executes the optimization and returns an
OptimizationResult. It raises an exception if the model directory or XML inputs are invalid, if a Bayesian candidate evaluation fails, or if all GA candidate evaluations fail. The GA treats an individual failed candidate as a worst-case result and continues when other evaluations succeed.
MaterialFraction¶
Defines a variable for the fraction of one nuclide or element in a material:
MaterialFraction(
material_id,
component,
bounds,
name=None,
component_type="nuclide",
basis="ao",
normalization_group=None,
)
material_idPositive OpenMC material ID to modify.
componentNuclide name such as
"U235"or element name such as"O".boundsInclusive lower and upper fraction values, each within
[0, 1]. Withoutnormalization_group, the fractions describe the whole material composition. With a group, the values describe the selected component’s share of that group. The applicable other entries are rescaled proportionally to fill the remainder.nameOptional unique parameter name used in result dictionaries and CSV column names. Defaults to
"{component}_{basis}_{material_id}".component_typeEither
"nuclide"or"element". Defaults to"nuclide".basisEither
"wo"for weight fraction or"ao"for atom fraction. Defaults to"ao", matching OpenMC’s default atom-percent basis. Every nuclide and element entry in the selected material must use the chosen basis inmaterials.xml.normalization_groupOptional tuple of component names of the same
component_type. When supplied,boundsdescribe the selected component’s fraction within this group. The total fraction of the group in the full material is preserved, as are all entries outside the group; the other group members are rescaled proportionally. Includecomponentin the group. For example,("U235", "U238")makes a U-235 fraction vary relative to total uranium while keeping the material’s total uranium amount fixed. Every named group component must already be present in the material.
VolumeFraction¶
Defines a physical-volume mixture by updating the target material with a specified volume share of the component material:
VolumeFraction(
target_material_id,
component_material_id,
bounds,
name=None,
)
target_material_idPositive OpenMC material ID that receives the mixture composition and density for each candidate. This is the output mixture material. It should be the material assigned to the geometry cell where the mixture is intended to be used. For a UO2–Gd2O3 fuel mixture, this is the UO2 fuel material ID already referenced by the fuel cell, or a separate mixture material ID if the geometry has been set up to use one.
component_material_idPositive OpenMC material ID whose recipe is added to the target mixture. Its composition and density are read from
materials.xml. For a UO2–Gd2O3 fuel mixture, this is the Gd2O3 material ID. It serves as an input recipe; the geometry cell does not need to reference this material separately.boundsInclusive lower and upper physical volume fractions in
[0, 1].nameOptional unique parameter name. Defaults to
"volume_fraction_{target_material_id}_{component_material_id}".
Both materials need explicit densities in g/cm3. The target material is
modified in the candidate XML and remains the material used by its geometry
cell. Increasing the component volume fraction replaces a corresponding
volume share of the target recipe; the component source material remains
available as its input recipe.
When converting atom-based element entries to mass fractions, the adapter
uses OpenMC’s openmc.data.atomic_weight for naturally occurring elements.
An element without a natural isotopic abundance has no unique average atomic
weight; represent it with explicit nuclide entries instead of an element
entry.
OptimizationResult¶
run() returns a frozen dataclass with these fields:
best_parametersMapping from design variable name to the best value found.
best_ppfPPF of the best candidate found during the run.
best_keffandbest_keff_std_devCombined k-effective estimate and its standard deviation from the best candidate’s OpenMC statepoint.
best_objective_lossWeighted normalized loss for the best feasible candidate. It is
Nonewhen a configured keff target was not met by any candidate.target_ppfThe stopping threshold passed to the optimizer, or
None.target_keffandkeff_toleranceThe k-effective target and absolute tolerance, or
Nonefor the target.keff_target_reachedWhether the best candidate is within the requested keff tolerance, or
Nonewhen no keff target was supplied.target_reachedWhether all configured targets were met. With only
target_keffset, this reports whether the best candidate is within its tolerance. With neither target configured, it isNone.historyList of per-generation dictionaries. Each contains the zero-based
generationindex, best and mean PPF, best and mean keff (when available), keff feasibility, weighted objective loss, andbest_parameters.summary_filePath to
optimization_summary.json.history_csvPath to
optimization_history.csv. Its rows contain the generation’s population size, best and mean PPF, best and mean keff, keff feasibility, best and mean objective loss, and best parameter values.candidates_csvPath to
optimization_candidates.csv. It contains one row per unique candidate that required an OpenMC run, including its PPF, keff and keff uncertainty, tally summary, and parameter values. Repeated identical vectors are served from the in-memory cache and are not written as additional unique rows.
Example¶
For a complete script with model setup, see Examples. For the behavior of the PPF calculation and genetic algorithm, see Theory and methods.