kika.sensitivities
The sensitivities module provides functionality for sensitivity analysis and working with perturbation data.
- kika.sensitivities.compute_sensitivity(inputfile: str, mctalfile: str, tally: int, zaid: int = None, label: str = '', material: int | None = None, cell: int = 0, pert_metadata: List[Tuple[int, int, int, int]] | None = None) SensitivityData[source]
Compute sensitivity coefficients from MCNP input and output files.
- Parameters:
inputfile (str) – Path to MCNP input file containing the PERT cards
mctalfile (str) – Path to MCNP MCTAL output file
tally (int) – Tally number to analyze
zaid (int, optional) – ZAID of the nuclide being perturbed. If None and pert_metadata is provided, extracted from the metadata (must be a single unique ZAID).
label (str) – Label for the sensitivity data set
material (int, optional) – Optional material number to filter perturbations by. If None, all perturbations are used (backward-compatible behavior).
cell (int) – Cell ID to use for multi-cell tallies. Default is 0, which is the total-over-cells bin in MCNP (added by the T parameter in the tally definition). For single-cell tallies this parameter is ignored.
pert_metadata (list of tuple, optional) – Optional list of (start_pert, end_pert, zaid, material) tuples. Assigns zaid and original_material to PERT cards in the given ranges. When provided, zaid and material can be inferred from the metadata.
- Returns:
Object containing computed sensitivity coefficients
- Return type:
SensitivityData
- Raises:
ValueError – If no zaid is given and none can be resolved from pert_metadata or PERT-card metadata, or if pert_metadata contains multiple ZAIDs (use compute_total_sensitivity instead).
- kika.sensitivities.compute_total_sensitivity(inputfile: str, mctalfile: str, tally: int, zaid: int = None, label: str = '', materials: List[int] | None = None, cell: int = 0, pert_metadata: List[Tuple[int, int, int, int]] | None = None) SensitivityData[source]
Compute total sensitivity by summing contributions from multiple materials.
For an isotope present in multiple materials, the total sensitivity is the sum of the per-material sensitivities:
\[S_{\text{total}}(E) = \sum_m S_m(E) = \sum_m \frac{c_{1,m}(E)}{r_0}\]Errors are propagated in quadrature (assuming statistical independence between material perturbations).
- Parameters:
inputfile (str) – Path to MCNP input file containing the PERT cards.
mctalfile (str) – Path to MCNP MCTAL output file.
tally (int) – Tally number to analyze.
zaid (int, optional) – ZAID of the nuclide being perturbed. If None and pert_metadata is provided, extracted from the metadata (all entries must share the same ZAID).
label (str) – Label for the resulting sensitivity data set.
materials (list of int, optional) – Material IDs to sum over. If None, auto-detected from the PERT cards in inputfile (or from pert_metadata if provided).
cell (int) – Cell ID to use for multi-cell tallies. Default is 0, which is the total-over-cells bin in MCNP (added by the T parameter in the tally definition). For single-cell tallies this parameter is ignored.
pert_metadata (list of tuple, optional) – List of (start_pert, end_pert, zaid, material) tuples. When provided, zaid and materials are extracted from the metadata.
- Returns:
Total sensitivity (summed across materials).
- Return type:
SensitivityData
- Raises:
ValueError – If no materials are found, or perturbation energy grids differ between materials.
- kika.sensitivities.plot_sens_comparison(sens_list: List[SensitivityData], energy: str | List[str] = None, reactions: List[int] | int = None, energy_range: tuple = None, xlog: bool = False, ylog: bool = False)[source]
Plot comparison of multiple sensitivity datasets.
- Parameters:
sens_list (List[SensitivityData]) – List of sensitivity datasets to compare.
energy (Union[str, List[str]], optional) – Energy string(s) to plot. If None, uses first dataset’s energies.
reactions (Union[List[int], int], optional) – Reaction number(s) to plot. If None, uses reactions from first dataset.
energy_range (tuple, optional) – Optional x-axis limits as (min, max).
xlog (bool, optional) – Whether to use logarithmic scale for x-axis. Default is False.
ylog (bool, optional) – Whether to use logarithmic scale for y-axis. Default is False.
- kika.sensitivities.create_sdf_data(sens_list: List[SensitivityData] | List[Tuple[SensitivityData, List[int]]], energy: str, title: str, response_values: Tuple[float, float] = None) SDFData[source]
Create a SDFData object from a list of SensitivityData objects.
- Parameters:
sens_list (Union[List[SensitivityData], List[Tuple[SensitivityData, List[int]]]]) – List of SensitivityData objects or tuples of (SensitivityData, reactions_list)
energy (str) – Energy value to use for sensitivity data
title (str) – Title for the SDF dataset
response_values (Tuple[float, float], optional) – Optional tuple of (r0, e0) to override the reference values from sensitivity data. This allows combining data from different sources that might have different base values. r0 is the unperturbed tally result (reference response value), e0 is the absolute error of the unperturbed tally result (not relative). Use this to ensure consistency when merging sensitivity data from different calculations.
- Returns:
SDFData object containing the combined sensitivity data
- Return type:
SDFData
- Raises:
ValueError – If pert_energies don’t match across sensitivity data objects
ValueError – If r0 and e0 values don’t match across sensitivity data objects and no response_values are provided
- class kika.sensitivities.SDFData(title: str, energy: str, pert_energies: ~typing.List[float], r0: float = None, e0: float = None, data: ~typing.List[~kika.sensitivities.sdf.SDFReactionData] = <factory>)[source]
Bases:
objectContainer for SDF data.
- Variables:
title – Title of the SDF dataset
energy – Energy value or label
pert_energies – List of perturbation energy boundaries
r0 – Unperturbed tally result (reference response value)
e0 – Absolute one-sigma uncertainty of the unperturbed tally result
data – List of reaction-specific sensitivity data
- classmethod can_merge(sdf_list: List[SDFData], energy: str | None = None, r0: float | None = None, e0: float | None = None) Tuple[bool, str][source]
Check whether a list of SDFData objects can be merged.
Runs the same validation as
merge()but never raises. Pass the same override parameters you would pass tomerge()to check whether the merge would succeed with those overrides.- Parameters:
- Returns:
(True, "")if the merge would succeed, or(False, reason)with a human-readable explanation otherwise.- Return type:
- e0: float = None
- group_inelastic_reactions(replace: bool = False, remove_originals: bool = True) None[source]
Group inelastic reactions (MT 51-91) into MT 4 for each nuclide.
This method combines all inelastic scattering reactions (MT 51-91) into the total inelastic scattering reaction (MT 4) for each nuclide.
- Parameters:
- Raises:
ValueError – If MT 4 already exists for a nuclide and replace=False
- classmethod merge(sdf_list: List[SDFData], title: str | None = None, energy: str | None = None, r0: float | None = None, e0: float | None = None) SDFData[source]
Merge multiple SDFData objects into a single one.
All SDFs must share the same perturbation energy grid. The merged object contains every
SDFReactionDataentry from the inputs; duplicate(zaid, mt)pairs are not allowed.- Parameters:
sdf_list (List[SDFData]) – List of SDFData objects to combine.
title (Optional[str]) – Override title. If None, uses the common title when all inputs match, otherwise joins distinct titles with
" + ".energy (Optional[str]) – Override energy label. If None, uses the common label when all inputs match, otherwise raises
ValueError.r0 (Optional[float]) – Override response value. If None, uses the common value when all inputs agree, otherwise raises
ValueError.e0 (Optional[float]) – Override absolute response uncertainty. If None, uses the common value when all inputs agree, otherwise raises
ValueError.
- Returns:
A new merged SDFData instance.
- Return type:
SDFData
- Raises:
ValueError – If sdf_list is empty, energy grids differ, r0/e0 values conflict (and none was given), energy labels differ (and none was given), or duplicate (zaid, mt) pairs are found.
- r0: float = None
- property relative_response_error: float | None
Return the relative response uncertainty
e0 / abs(r0).
- to_plot_data(index: int = None, zaid: int = None, mt: int = None, per_lethargy: bool = True, uncertainty: bool = True, sigma: float = 1.0, uncertainty_style: str = 'errorbar', label: str = None, **styling_kwargs) MultigroupCrossSectionPlotData | Tuple[MultigroupCrossSectionPlotData, UncertaintyBand][source]
Convert a reaction’s sensitivity data into PlotData objects.
Look up a reaction either by index into
dataor by (zaid, mt) pair, then delegate toSDFReactionData.to_plot_data().- Parameters:
index (int, optional) – Direct index into
self.data.zaid (int, optional) – ZAID of the nuclide (requires mt as well).
mt (int, optional) – MT reaction number (requires zaid as well).
per_lethargy (bool) – Normalise by lethargy width (default
True).uncertainty (bool) – Include an
UncertaintyBand(defaultTrue).sigma (float) – Sigma multiplier for the uncertainty band.
uncertainty_style (str) – Rendering style for the uncertainty band:
'errorbar'(default for sensitivity data) or'band'.label (str, optional) – Legend label (auto-generated if None).
styling_kwargs – Forwarded to
MultigroupCrossSectionPlotData.
- Returns:
See
SDFReactionData.to_plot_data().- Return type:
MultigroupCrossSectionPlotData or Tuple[MultigroupCrossSectionPlotData, UncertaintyBand]
- Raises:
ValueError – If neither index nor (zaid, mt) is given, or if the requested reaction is not found.
- to_sensitivity_profile() SensitivityProfile[source]
Return the system-total data as a format-neutral sensitivity profile.
SDF entries with non-zero
unitorregionidentify auxiliary mixture/region profiles and are deliberately excluded from UQ vectors.
- write_file(output_dir: str | None = None)[source]
Write the SDF data using the standard SCALE uncertainty convention.
- Parameters:
output_dir (Optional[str]) – Directory where the SDF file will be written. If None, uses current directory.
- title: str
- energy: str
- data: List[SDFReactionData]
- class kika.sensitivities.SDFReactionData(zaid: int, mt: int, sensitivity: List[float], error: List[float], reaction_name: str | None = None, unit: int | None = None, region: int | None = None)[source]
Bases:
objectContainer for sensitivity data for a specific nuclide and reaction.
- Variables:
zaid – ZAID of the nuclide
mt – MT reaction number
sensitivity – List of sensitivity coefficients
error – List of absolute one-sigma standard deviations
nuclide – Nuclide symbol (calculated from ZAID)
reaction_name – Reaction name (calculated from MT)
- classmethod from_relative_errors(*, zaid: int, mt: int, sensitivity, relative_error, reaction_name: str | None = None, unit: int | None = None, region: int | None = None) SDFReactionData[source]
Build reaction data from relative one-sigma errors.
- property relative_error: List[float]
Return the relative standard deviation for each sensitivity group.
- to_plot_data(pert_energies, per_lethargy: bool = True, uncertainty: bool = True, sigma: float = 1.0, uncertainty_style: str = 'errorbar', label: str = None, **styling_kwargs) MultigroupCrossSectionPlotData | Tuple[MultigroupCrossSectionPlotData, UncertaintyBand][source]
Convert sensitivity data for this reaction into PlotData objects.
Returns a
MultigroupCrossSectionPlotData(step plot) and, optionally, anUncertaintyBandsuitable forPlotBuilder.- Parameters:
pert_energies (array-like) – Energy bin boundaries (n+1 values, ascending order in MeV).
per_lethargy (bool) – If True, normalise sensitivity values by the lethargy width of each bin (matches
Coefficients.plot()behaviour).uncertainty (bool) – If True, return an
UncertaintyBandalongside the nominal data.sigma (float) – Sigma multiplier for the uncertainty band.
uncertainty_style (str) – Rendering style for the uncertainty band:
'errorbar'(default for sensitivity data) or'band'.label (str, optional) – Legend label. Auto-generated as
"<nuclide> <reaction_name>"(e.g."Fe-56 (n,el)") when None.styling_kwargs – Forwarded to
MultigroupCrossSectionPlotData(color,linestyle,linewidth, etc.).
- Returns:
MultigroupCrossSectionPlotDatawhen uncertainty=False, or(MultigroupCrossSectionPlotData, UncertaintyBand)when uncertainty=True.- Return type:
MultigroupCrossSectionPlotData or Tuple[MultigroupCrossSectionPlotData, UncertaintyBand]
- zaid: int
- mt: int
- nuclide: str
- class kika.sensitivities.SensitivityProfile(energy_grid: ~numpy.ndarray, reactions: ~typing.Tuple[~kika.sensitivities.profile.SensitivityReaction, ...], energy_unit: ~typing.Literal['eV', 'MeV'] = 'MeV', response: float | None = None, response_uncertainty: float | None = None, label: str | None = None, metadata: ~typing.Mapping[str, ~typing.Any] = <factory>)[source]
Bases:
objectValidated sensitivity data independent of SDF or database storage.
Sensitivities are dimensionless relative coefficients.
uncertaintyis the absolute one-sigma uncertainty on each sensitivity coefficient.- energy_unit: Literal['eV', 'MeV'] = 'MeV'
- property n_groups: int
- energy_grid: ndarray
- reactions: Tuple[SensitivityReaction, ...]
- class kika.sensitivities.SensitivityReaction(zaid: int, mt: int, sensitivity: ndarray, uncertainty: ndarray | None = None, label: str | None = None)[source]
Bases:
objectOne format-neutral multigroup sensitivity profile.
- zaid: int
- mt: int
- sensitivity: ndarray
- class kika.sensitivities.SensitivityData(tally_id: int, pert_energies: list[float], zaid: int, label: str, tally_name: str = None, data: ~typing.Dict[str, ~typing.Dict[int, ~kika.sensitivities.sensitivity.Coefficients]] = None, coefficients: ~typing.Dict[str, ~typing.Dict[int, ~kika.sensitivities.sensitivity.TaylorCoefficients]] = <factory>)[source]
Bases:
objectContainer class for sensitivity analysis data.
- Variables:
tally_id – ID of the tally used for sensitivity calculation
pert_energies – List of perturbation energy boundaries
zaid – ZAID of the nuclide for which sensitivities were calculated
label – Label for the sensitivity data set
tally_name – Name of the tally
data – Nested dictionary containing sensitivity coefficients organized by energy and reaction number
coefficients – Dictionary containing Taylor series coefficients organized by energy and reaction number
lethargy – List of lethargy intervals between perturbation energies
energies – List of energy values used as keys in the data dictionary
reactions – Sorted list of unique reaction numbers found in the data
nuclide – Nuclide symbol for the ZAID
- plot_perturbed_response(energy: str | List[str] = None, reaction: List[int] | int = None, p_range: tuple = (-20, 20), n_points: int = 100, top_n: int = 3, e_bins: List[int] = None, n_sigma: float = 1.0, print_coefficients: bool = False)[source]
Plot perturbed response as a function of perturbation magnitude.
Compares first-order approximation R(p) = R0 + c1*p with second-order approximation R(p) = R0 + c1*p + c2*p^2.
- Parameters:
energy (Union[str, List[str]], optional) – Energy string(s) to plot. If None, plots all energies
reaction (Union[List[int], int], optional) – Reaction number(s) to plot. If None, plots all reactions
p_range (tuple, optional) – Range of perturbation magnitudes as (min%, max%) in percent
n_points (int, optional) – Number of points to evaluate for plotting
top_n (int, optional) – Number of perturbation energy bins with highest nonlinearity to show. If 0, shows all bins.
e_bins (List[int], optional) – Specific indices of perturbation energy bins to plot. Overrides top_n if provided.
n_sigma (float, optional) – Number of standard deviations to show in error bands
print_coefficients (bool, optional) – Whether to print detailed coefficient info to console instead of on plot
- Raises:
ValueError – If sensitivity data does not contain Taylor coefficients
ValueError – If specified energies are not found in the data
- plot_ratio(energy: str | List[str] = None, reaction: List[int] | int = None, top_n: int = 5)[source]
Plot ratio of second-order to first-order sensitivity coefficients.
- The ratio is calculated as:
R = (c2 * p) / c1
- Where:
c2 is the second-order coefficient
c1 is the first-order coefficient
p is the perturbation fraction
- Parameters:
- Raises:
ValueError – If sensitivity data does not contain Taylor coefficients
ValueError – If specified energies are not found in the data
- plot_second_order_contribution(energy: str | List[str] = None, reaction: List[int] | int = None, p_range: tuple = (-20, 20), n_points: int = 100, top_n: int = 3, e_bins: List[int] = None, n_sigma: float = 1.0, print_coefficients: bool = False)[source]
Plot the contribution of second-order term as percentage of the total response.
This shows how much of the total second-order response comes from the second-order term (c2*p²), which indicates the error introduced when using only first-order approximation.
- Parameters:
energy (Union[str, List[str]], optional) – Energy string(s) to plot. If None, plots all energies
reaction (Union[List[int], int], optional) – Reaction number(s) to plot. If None, plots all reactions
p_range (tuple, optional) – Range of perturbation magnitudes as (min%, max%) in percent
n_points (int, optional) – Number of points to evaluate for plotting
top_n (int, optional) – Number of perturbation energy bins with highest second-order contribution to show. If 0, shows all bins.
e_bins (List[int], optional) – Specific indices of perturbation energy bins to plot. Overrides top_n if provided.
n_sigma (float, optional) – Number of standard deviations to show in error bands
print_coefficients (bool, optional) – Whether to print detailed coefficient info to console instead of on plot
- Raises:
ValueError – If sensitivity data does not contain Taylor coefficients
ValueError – If specified energies are not found in the data
- plot_sensitivity(energy: str | List[str] = None, reaction: List[int] | int = None, energy_range: tuple = None, xlog: bool = False, ylog: bool = False)[source]
Plot sensitivity coefficients for specified energies and reactions.
- Parameters:
energy (Union[str, List[str]], optional) – Energy string(s) to plot. If None, plots all energies.
reaction (Union[List[int], int], optional) – Reaction number(s) to plot. If None, plots all reactions.
energy_range (tuple, optional) – Optional x-axis limits as (min, max).
xlog (bool, optional) – Whether to use logarithmic scale for x-axis. Default is False.
ylog (bool, optional) – Whether to use logarithmic scale for y-axis. Default is False.
- Raises:
ValueError – If specified energies are not found in the data.
- tally_name: str = None
- to_dataframe() DataFrame[source]
Export sensitivity data as a pandas DataFrame for plotting.
- Returns:
DataFrame with the following columns: - det_energy: Detector energy range string (e.g., “0.00e+00_1.00e-01”) or ‘integral’ - energy_lower: Lower energy boundary parsed from det_energy string (None for ‘integral’) - energy_upper: Upper energy boundary parsed from det_energy string (None for ‘integral’) - reaction: Reaction number (MT) - e_lower: Lower boundary of perturbation energy bin - e_upper: Upper boundary of perturbation energy bin - sensitivity: Sensitivity per lethargy value - error: Relative error value for the sensitivity - label: Sensitivity data label - tally_name: Name of the tally
- Return type:
pd.DataFrame
- tally_id: int
- zaid: int
- label: str
- nuclide: str
- class kika.sensitivities.TaylorCoefficients(energy: str, reaction: int, pert_energies: list[float], c1: list[float], c2: list[float], ratio: list[float], c2_errors: list[float], c1_errors: list[float])[source]
Bases:
objectContainer for Taylor series expansion coefficients.
- Variables:
energy – Energy range string in format “lower_upper” (e.g., “0.00e+00_1.00e-01”)
reaction – Reaction number
pert_energies – Perturbation energy boundaries
c1 – First-order Taylor coefficients
c2 – Second-order Taylor coefficients
ratio – Ratio of c2/c1 for each energy bin
c2_errors – Errors of second-order Taylor coefficients
c1_errors – Errors of first-order Taylor coefficients
- calculate_nonlinearity(p: float) float[source]
Calculate the nonlinearity factor at a specific perturbation.
The nonlinearity factor is (c2*p)/c1, which represents the ratio of second-order to first-order term at perturbation magnitude p.
- calculate_nonlinearity_by_bin(p: float) list[source]
Calculate the nonlinearity factor for each energy bin at specific perturbation.
The nonlinearity factor is (c2*p)/c1, which represents the ratio of second-order to first-order term at perturbation magnitude p.
- plot(ax=None, title=None, top_n=5)[source]
Plot the nonlinearity factor vs perturbation magnitude.
The nonlinearity factor is plotted using absolute values for better comparison, as the sign of the ratio doesn’t provide valuable information in this context.
- energy: str
- reaction: int
- class kika.sensitivities.Coefficients(energy: str, reaction: int, pert_energies: list[float], values: list[float], errors: list[float], r0: float = None, e0: float = None, values_second: list[float] = None, errors_second: list[float] = None)[source]
Bases:
objectContainer for sensitivity coefficients for a specific energy and reaction.
- Variables:
energy – Energy range string in format “lower_upper” (e.g., “0.00e+00_1.00e-01”)
reaction – Reaction number
pert_energies – Perturbation energy boundaries
values – Sensitivity coefficient values (first-order)
errors – Relative errors for the sensitivity coefficients (first-order)
r0 – Unperturbed tally result
e0 – Unperturbed tally error
values_second – Second-order sensitivity coefficient values
errors_second – Relative errors for the second-order sensitivity coefficients
- e0: float = None
- property lethargy
Calculate lethargy intervals between perturbation energies.
- Returns:
List of lethargy intervals
- Return type:
List[float]
- plot(ax=None, xlim=None, xlog=False)[source]
Create a new plot of sensitivity coefficients.
- Parameters:
- Returns:
The axis containing the plot
- Return type:
matplotlib.axes.Axes
- r0: float = None
- to_dataframe() DataFrame[source]
Convert coefficients data to a pandas DataFrame.
- Returns:
DataFrame with columns: - energy: Energy range string (detector energy) - reaction: Reaction number (MT) - e_lower: Lower boundary of perturbation energy bin - e_upper: Upper boundary of perturbation energy bin - sensitivity: Sensitivity coefficient value - error: Relative error of the coefficient
- Return type:
pd.DataFrame
- to_plot_data(per_lethargy: bool = True, uncertainty: bool = True, sigma: float = 1.0, uncertainty_style: str = 'errorbar', label: str = None, **styling_kwargs) MultigroupCrossSectionPlotData | Tuple[MultigroupCrossSectionPlotData, UncertaintyBand][source]
Convert sensitivity coefficients into PlotData objects.
Returns a
MultigroupCrossSectionPlotData(step plot) and, optionally, anUncertaintyBandsuitable forPlotBuilder.- Parameters:
per_lethargy (bool) – If True, normalise sensitivity values by the lethargy width of each bin (matches
Coefficients.plot()behaviour).uncertainty (bool) – If True, return an
UncertaintyBandalongside the nominal data.sigma (float) – Sigma multiplier for the uncertainty band.
uncertainty_style (str) – Rendering style for the uncertainty band:
'errorbar'(default) or'band'.label (str, optional) – Legend label. Auto-generated as
"<reaction_name> (MT<reaction>)"when None.styling_kwargs – Forwarded to
MultigroupCrossSectionPlotData(color,linestyle,linewidth, etc.).
- Returns:
MultigroupCrossSectionPlotDatawhen uncertainty=False, or(MultigroupCrossSectionPlotData, UncertaintyBand)when uncertainty=True.- Return type:
MultigroupCrossSectionPlotData or Tuple[MultigroupCrossSectionPlotData, UncertaintyBand]
- property values_per_lethargy
Calculate sensitivity coefficients per unit lethargy.
- Returns:
Sensitivity coefficients normalized by lethargy intervals
- Return type:
List[float]
- energy: str
- reaction: int
- exception kika.sensitivities.CondensationError[source]
Bases:
ValueErrorRaised when a sensitivity profile cannot be condensed exactly.
- class kika.sensitivities.CondensationReport(source_groups: int, target_groups: int, source_energy_grid: Tuple[float, ...], target_energy_grid: Tuple[float, ...], source_energy_unit: Literal['eV', 'MeV'], target_energy_unit: Literal['eV', 'MeV'], boundary_indices: Tuple[int, ...], energy_rtol: float, uncertainty_method: str, assumptions: Tuple[str, ...], max_integral_drift: float)[source]
Bases:
objectDiagnostics and assumptions for one exact condensation operation.
- source_groups: int
- target_groups: int
- source_energy_unit: Literal['eV', 'MeV']
- target_energy_unit: Literal['eV', 'MeV']
- energy_rtol: float
- uncertainty_method: str
- max_integral_drift: float
- class kika.sensitivities.CondensationResult(profile: SensitivityProfile, operator: ndarray, report: CondensationReport)[source]
Bases:
objectA condensed profile together with its operator and diagnostics.
- profile: SensitivityProfile
- operator: ndarray
- report: CondensationReport
- kika.sensitivities.condense_sensitivity_profile(profile: SensitivityProfile, target_grid: Iterable[float], *, target_energy_unit: Literal['eV', 'MeV'] | None = None, energy_rtol: float = 1e-05) CondensationResult[source]
Condense a sensitivity profile onto an exactly nested coarser grid.
Group-wise sensitivity coefficients are integral contributions, so source groups inside each target group are summed. Absolute one-sigma statistical uncertainties are combined in quadrature, which assumes independent source- group estimates. Unknown uncertainties remain unknown.
The operation is deliberately strict: the target grid must span the same range and every target boundary must be present in the source grid after explicit unit conversion. Non-nested grid projection is not performed.
- Parameters:
profile – Validated, format-neutral source profile.
target_grid – Ascending boundaries for the coarser output grid.
target_energy_unit – Unit of
target_gridand of the returned profile. Defaults to the source profile unit.energy_rtol – Relative tolerance used only to identify physically equal boundaries. The default covers the six-digit boundary rounding used by DICE SDFs.
- kika.sensitivities.sensitivity_to_plot_data(pert_energies, sensitivity, error=None, zaid: int = None, mt: int = None, nuclide: str = None, reaction_name: str = None, per_lethargy: bool = True, uncertainty: bool = True, sigma: float = 1.0, uncertainty_style: str = 'errorbar', label: str = None, **styling_kwargs) MultigroupCrossSectionPlotData | Tuple[MultigroupCrossSectionPlotData, UncertaintyBand][source]
Build PlotData objects from raw sensitivity arrays.
Shared core behind
SDFReactionData.to_plot_data(); usable directly on plain arrays (e.g. the dicts returned bykika.benchmarks.database.BenchmarksDatabase.get_profile_vector()) so both SDF objects and benchmark profiles render through the same code path.Produces a
MultigroupCrossSectionPlotDatastep plot and, when uncertainty is True and per-group absolute standard deviations are available, anUncertaintyBand, both suitable forPlotBuilder.- Parameters:
pert_energies – Energy bin boundaries (n+1 values, ascending, MeV).
sensitivity – Per-group sensitivity coefficients (n values).
error – Per-group absolute standard deviations (n values). If
None(or uncertainty is False) no uncertainty band is returned.zaid – ZAID, used for the plot metadata and the default label.
mt – MT reaction number, used for metadata and the default label.
nuclide – Nuclide symbol for the default label (e.g.
"Fe-56").reaction_name – Reaction label for the default label (e.g.
"(n,el)").per_lethargy – Normalise by the lethargy width of each bin (default True).
uncertainty – Return an
UncertaintyBandwhen error data is present.sigma – Sigma multiplier for the uncertainty band.
uncertainty_style –
'errorbar'(default) or'band'.label – Legend label; auto-generated from nuclide/reaction when None.
styling_kwargs – Forwarded to
MultigroupCrossSectionPlotData.
- Returns:
MultigroupCrossSectionPlotDataalone when no uncertainty band is produced, otherwise(MultigroupCrossSectionPlotData, UncertaintyBand).
Submodules
kika.sensitivities.sensitivity
- class kika.sensitivities.sensitivity.TaylorCoefficients(energy: str, reaction: int, pert_energies: list[float], c1: list[float], c2: list[float], ratio: list[float], c2_errors: list[float], c1_errors: list[float])[source]
Bases:
objectContainer for Taylor series expansion coefficients.
- Variables:
energy – Energy range string in format “lower_upper” (e.g., “0.00e+00_1.00e-01”)
reaction – Reaction number
pert_energies – Perturbation energy boundaries
c1 – First-order Taylor coefficients
c2 – Second-order Taylor coefficients
ratio – Ratio of c2/c1 for each energy bin
c2_errors – Errors of second-order Taylor coefficients
c1_errors – Errors of first-order Taylor coefficients
- energy: str
- reaction: int
- calculate_nonlinearity(p: float) float[source]
Calculate the nonlinearity factor at a specific perturbation.
The nonlinearity factor is (c2*p)/c1, which represents the ratio of second-order to first-order term at perturbation magnitude p.
- calculate_nonlinearity_by_bin(p: float) list[source]
Calculate the nonlinearity factor for each energy bin at specific perturbation.
The nonlinearity factor is (c2*p)/c1, which represents the ratio of second-order to first-order term at perturbation magnitude p.
- plot(ax=None, title=None, top_n=5)[source]
Plot the nonlinearity factor vs perturbation magnitude.
The nonlinearity factor is plotted using absolute values for better comparison, as the sign of the ratio doesn’t provide valuable information in this context.
- class kika.sensitivities.sensitivity.SensitivityData(tally_id: int, pert_energies: list[float], zaid: int, label: str, tally_name: str = None, data: ~typing.Dict[str, ~typing.Dict[int, ~kika.sensitivities.sensitivity.Coefficients]] = None, coefficients: ~typing.Dict[str, ~typing.Dict[int, ~kika.sensitivities.sensitivity.TaylorCoefficients]] = <factory>)[source]
Bases:
objectContainer class for sensitivity analysis data.
- Variables:
tally_id – ID of the tally used for sensitivity calculation
pert_energies – List of perturbation energy boundaries
zaid – ZAID of the nuclide for which sensitivities were calculated
label – Label for the sensitivity data set
tally_name – Name of the tally
data – Nested dictionary containing sensitivity coefficients organized by energy and reaction number
coefficients – Dictionary containing Taylor series coefficients organized by energy and reaction number
lethargy – List of lethargy intervals between perturbation energies
energies – List of energy values used as keys in the data dictionary
reactions – Sorted list of unique reaction numbers found in the data
nuclide – Nuclide symbol for the ZAID
- tally_id: int
- zaid: int
- label: str
- tally_name: str = None
- nuclide: str
- plot_sensitivity(energy: str | List[str] = None, reaction: List[int] | int = None, energy_range: tuple = None, xlog: bool = False, ylog: bool = False)[source]
Plot sensitivity coefficients for specified energies and reactions.
- Parameters:
energy (Union[str, List[str]], optional) – Energy string(s) to plot. If None, plots all energies.
reaction (Union[List[int], int], optional) – Reaction number(s) to plot. If None, plots all reactions.
energy_range (tuple, optional) – Optional x-axis limits as (min, max).
xlog (bool, optional) – Whether to use logarithmic scale for x-axis. Default is False.
ylog (bool, optional) – Whether to use logarithmic scale for y-axis. Default is False.
- Raises:
ValueError – If specified energies are not found in the data.
- plot_ratio(energy: str | List[str] = None, reaction: List[int] | int = None, top_n: int = 5)[source]
Plot ratio of second-order to first-order sensitivity coefficients.
- The ratio is calculated as:
R = (c2 * p) / c1
- Where:
c2 is the second-order coefficient
c1 is the first-order coefficient
p is the perturbation fraction
- Parameters:
- Raises:
ValueError – If sensitivity data does not contain Taylor coefficients
ValueError – If specified energies are not found in the data
- to_dataframe() DataFrame[source]
Export sensitivity data as a pandas DataFrame for plotting.
- Returns:
DataFrame with the following columns: - det_energy: Detector energy range string (e.g., “0.00e+00_1.00e-01”) or ‘integral’ - energy_lower: Lower energy boundary parsed from det_energy string (None for ‘integral’) - energy_upper: Upper energy boundary parsed from det_energy string (None for ‘integral’) - reaction: Reaction number (MT) - e_lower: Lower boundary of perturbation energy bin - e_upper: Upper boundary of perturbation energy bin - sensitivity: Sensitivity per lethargy value - error: Relative error value for the sensitivity - label: Sensitivity data label - tally_name: Name of the tally
- Return type:
pd.DataFrame
- plot_perturbed_response(energy: str | List[str] = None, reaction: List[int] | int = None, p_range: tuple = (-20, 20), n_points: int = 100, top_n: int = 3, e_bins: List[int] = None, n_sigma: float = 1.0, print_coefficients: bool = False)[source]
Plot perturbed response as a function of perturbation magnitude.
Compares first-order approximation R(p) = R0 + c1*p with second-order approximation R(p) = R0 + c1*p + c2*p^2.
- Parameters:
energy (Union[str, List[str]], optional) – Energy string(s) to plot. If None, plots all energies
reaction (Union[List[int], int], optional) – Reaction number(s) to plot. If None, plots all reactions
p_range (tuple, optional) – Range of perturbation magnitudes as (min%, max%) in percent
n_points (int, optional) – Number of points to evaluate for plotting
top_n (int, optional) – Number of perturbation energy bins with highest nonlinearity to show. If 0, shows all bins.
e_bins (List[int], optional) – Specific indices of perturbation energy bins to plot. Overrides top_n if provided.
n_sigma (float, optional) – Number of standard deviations to show in error bands
print_coefficients (bool, optional) – Whether to print detailed coefficient info to console instead of on plot
- Raises:
ValueError – If sensitivity data does not contain Taylor coefficients
ValueError – If specified energies are not found in the data
- plot_second_order_contribution(energy: str | List[str] = None, reaction: List[int] | int = None, p_range: tuple = (-20, 20), n_points: int = 100, top_n: int = 3, e_bins: List[int] = None, n_sigma: float = 1.0, print_coefficients: bool = False)[source]
Plot the contribution of second-order term as percentage of the total response.
This shows how much of the total second-order response comes from the second-order term (c2*p²), which indicates the error introduced when using only first-order approximation.
- Parameters:
energy (Union[str, List[str]], optional) – Energy string(s) to plot. If None, plots all energies
reaction (Union[List[int], int], optional) – Reaction number(s) to plot. If None, plots all reactions
p_range (tuple, optional) – Range of perturbation magnitudes as (min%, max%) in percent
n_points (int, optional) – Number of points to evaluate for plotting
top_n (int, optional) – Number of perturbation energy bins with highest second-order contribution to show. If 0, shows all bins.
e_bins (List[int], optional) – Specific indices of perturbation energy bins to plot. Overrides top_n if provided.
n_sigma (float, optional) – Number of standard deviations to show in error bands
print_coefficients (bool, optional) – Whether to print detailed coefficient info to console instead of on plot
- Raises:
ValueError – If sensitivity data does not contain Taylor coefficients
ValueError – If specified energies are not found in the data
- class kika.sensitivities.sensitivity.Coefficients(energy: str, reaction: int, pert_energies: list[float], values: list[float], errors: list[float], r0: float = None, e0: float = None, values_second: list[float] = None, errors_second: list[float] = None)[source]
Bases:
objectContainer for sensitivity coefficients for a specific energy and reaction.
- Variables:
energy – Energy range string in format “lower_upper” (e.g., “0.00e+00_1.00e-01”)
reaction – Reaction number
pert_energies – Perturbation energy boundaries
values – Sensitivity coefficient values (first-order)
errors – Relative errors for the sensitivity coefficients (first-order)
r0 – Unperturbed tally result
e0 – Unperturbed tally error
values_second – Second-order sensitivity coefficient values
errors_second – Relative errors for the second-order sensitivity coefficients
- energy: str
- reaction: int
- r0: float = None
- e0: float = None
- property lethargy
Calculate lethargy intervals between perturbation energies.
- Returns:
List of lethargy intervals
- Return type:
List[float]
- property values_per_lethargy
Calculate sensitivity coefficients per unit lethargy.
- Returns:
Sensitivity coefficients normalized by lethargy intervals
- Return type:
List[float]
- to_dataframe() DataFrame[source]
Convert coefficients data to a pandas DataFrame.
- Returns:
DataFrame with columns: - energy: Energy range string (detector energy) - reaction: Reaction number (MT) - e_lower: Lower boundary of perturbation energy bin - e_upper: Upper boundary of perturbation energy bin - sensitivity: Sensitivity coefficient value - error: Relative error of the coefficient
- Return type:
pd.DataFrame
- to_plot_data(per_lethargy: bool = True, uncertainty: bool = True, sigma: float = 1.0, uncertainty_style: str = 'errorbar', label: str = None, **styling_kwargs) MultigroupCrossSectionPlotData | Tuple[MultigroupCrossSectionPlotData, UncertaintyBand][source]
Convert sensitivity coefficients into PlotData objects.
Returns a
MultigroupCrossSectionPlotData(step plot) and, optionally, anUncertaintyBandsuitable forPlotBuilder.- Parameters:
per_lethargy (bool) – If True, normalise sensitivity values by the lethargy width of each bin (matches
Coefficients.plot()behaviour).uncertainty (bool) – If True, return an
UncertaintyBandalongside the nominal data.sigma (float) – Sigma multiplier for the uncertainty band.
uncertainty_style (str) – Rendering style for the uncertainty band:
'errorbar'(default) or'band'.label (str, optional) – Legend label. Auto-generated as
"<reaction_name> (MT<reaction>)"when None.styling_kwargs – Forwarded to
MultigroupCrossSectionPlotData(color,linestyle,linewidth, etc.).
- Returns:
MultigroupCrossSectionPlotDatawhen uncertainty=False, or(MultigroupCrossSectionPlotData, UncertaintyBand)when uncertainty=True.- Return type:
MultigroupCrossSectionPlotData or Tuple[MultigroupCrossSectionPlotData, UncertaintyBand]
- plot(ax=None, xlim=None, xlog=False)[source]
Create a new plot of sensitivity coefficients.
- Parameters:
- Returns:
The axis containing the plot
- Return type:
matplotlib.axes.Axes
kika.sensitivities.sensitivity_processing
Utility functions for sensitivity analysis and processing.
This module contains functions for computing sensitivity coefficients from MCNP files, creating SDF data objects from sensitivity data, and other related utility functions.
- kika.sensitivities.sensitivity_processing.compute_sensitivity(inputfile: str, mctalfile: str, tally: int, zaid: int = None, label: str = '', material: int | None = None, cell: int = 0, pert_metadata: List[Tuple[int, int, int, int]] | None = None) SensitivityData[source]
Compute sensitivity coefficients from MCNP input and output files.
- Parameters:
inputfile (str) – Path to MCNP input file containing the PERT cards
mctalfile (str) – Path to MCNP MCTAL output file
tally (int) – Tally number to analyze
zaid (int, optional) – ZAID of the nuclide being perturbed. If None and pert_metadata is provided, extracted from the metadata (must be a single unique ZAID).
label (str) – Label for the sensitivity data set
material (int, optional) – Optional material number to filter perturbations by. If None, all perturbations are used (backward-compatible behavior).
cell (int) – Cell ID to use for multi-cell tallies. Default is 0, which is the total-over-cells bin in MCNP (added by the T parameter in the tally definition). For single-cell tallies this parameter is ignored.
pert_metadata (list of tuple, optional) – Optional list of (start_pert, end_pert, zaid, material) tuples. Assigns zaid and original_material to PERT cards in the given ranges. When provided, zaid and material can be inferred from the metadata.
- Returns:
Object containing computed sensitivity coefficients
- Return type:
SensitivityData
- Raises:
ValueError – If no zaid is given and none can be resolved from pert_metadata or PERT-card metadata, or if pert_metadata contains multiple ZAIDs (use compute_total_sensitivity instead).
- kika.sensitivities.sensitivity_processing.compute_total_sensitivity(inputfile: str, mctalfile: str, tally: int, zaid: int = None, label: str = '', materials: List[int] | None = None, cell: int = 0, pert_metadata: List[Tuple[int, int, int, int]] | None = None) SensitivityData[source]
Compute total sensitivity by summing contributions from multiple materials.
For an isotope present in multiple materials, the total sensitivity is the sum of the per-material sensitivities:
\[S_{\text{total}}(E) = \sum_m S_m(E) = \sum_m \frac{c_{1,m}(E)}{r_0}\]Errors are propagated in quadrature (assuming statistical independence between material perturbations).
- Parameters:
inputfile (str) – Path to MCNP input file containing the PERT cards.
mctalfile (str) – Path to MCNP MCTAL output file.
tally (int) – Tally number to analyze.
zaid (int, optional) – ZAID of the nuclide being perturbed. If None and pert_metadata is provided, extracted from the metadata (all entries must share the same ZAID).
label (str) – Label for the resulting sensitivity data set.
materials (list of int, optional) – Material IDs to sum over. If None, auto-detected from the PERT cards in inputfile (or from pert_metadata if provided).
cell (int) – Cell ID to use for multi-cell tallies. Default is 0, which is the total-over-cells bin in MCNP (added by the T parameter in the tally definition). For single-cell tallies this parameter is ignored.
pert_metadata (list of tuple, optional) – List of (start_pert, end_pert, zaid, material) tuples. When provided, zaid and materials are extracted from the metadata.
- Returns:
Total sensitivity (summed across materials).
- Return type:
SensitivityData
- Raises:
ValueError – If no materials are found, or perturbation energy grids differ between materials.
- kika.sensitivities.sensitivity_processing.plot_sens_comparison(sens_list: List[SensitivityData], energy: str | List[str] = None, reactions: List[int] | int = None, energy_range: tuple = None, xlog: bool = False, ylog: bool = False)[source]
Plot comparison of multiple sensitivity datasets.
- Parameters:
sens_list (List[SensitivityData]) – List of sensitivity datasets to compare.
energy (Union[str, List[str]], optional) – Energy string(s) to plot. If None, uses first dataset’s energies.
reactions (Union[List[int], int], optional) – Reaction number(s) to plot. If None, uses reactions from first dataset.
energy_range (tuple, optional) – Optional x-axis limits as (min, max).
xlog (bool, optional) – Whether to use logarithmic scale for x-axis. Default is False.
ylog (bool, optional) – Whether to use logarithmic scale for y-axis. Default is False.
- kika.sensitivities.sensitivity_processing.create_sdf_data(sens_list: List[SensitivityData] | List[Tuple[SensitivityData, List[int]]], energy: str, title: str, response_values: Tuple[float, float] = None) SDFData[source]
Create a SDFData object from a list of SensitivityData objects.
- Parameters:
sens_list (Union[List[SensitivityData], List[Tuple[SensitivityData, List[int]]]]) – List of SensitivityData objects or tuples of (SensitivityData, reactions_list)
energy (str) – Energy value to use for sensitivity data
title (str) – Title for the SDF dataset
response_values (Tuple[float, float], optional) – Optional tuple of (r0, e0) to override the reference values from sensitivity data. This allows combining data from different sources that might have different base values. r0 is the unperturbed tally result (reference response value), e0 is the absolute error of the unperturbed tally result (not relative). Use this to ensure consistency when merging sensitivity data from different calculations.
- Returns:
SDFData object containing the combined sensitivity data
- Return type:
SDFData
- Raises:
ValueError – If pert_energies don’t match across sensitivity data objects
ValueError – If r0 and e0 values don’t match across sensitivity data objects and no response_values are provided
- kika.sensitivities.sensitivity_processing.create_sdf_from_serpent(serpent_file: SensitivityFile | List[SensitivityFile], response_name: str | List[str], title: str, material_filter: str | List[str] = None, nuclide_filter: int | List[int] = None, mt_filter: int | List[int] = None, response_values: Tuple[float, float] = None) SDFData[source]
Create a SDFData object from SERPENT sensitivity results.
Note: SERPENT provides relative errors, which are converted once to absolute standard deviations when constructing SDFReactionData.
- Parameters:
serpent_file (Union[SensitivityFile, List[SensitivityFile]]) – SERPENT sensitivity file object(s). Can be a single file or list of files.
response_name (Union[str, List[str]]) – Name(s) of the response to extract. Can be a single response name (used for all files) or a list matching the number of files. Examples: ‘sens_ratio_BIN_2’ or [‘sens_ratio_BIN_1’, ‘sens_ratio_BIN_2’]
title (str) – Title for the SDF dataset
material_filter (Union[str, List[str]], optional) – Material name(s) to include. If None, uses all materials.
nuclide_filter (Union[int, List[int]], optional) – Nuclide ZAI(s) to include. If None, uses all nuclides.
mt_filter (Union[int, List[int]], optional) – MT reaction number(s) to include. If None, uses all MT reactions (including Legendre coefficients MT=4001+).
response_values (Tuple[float, float], optional) – Tuple of (r0, e0) reference response values. If None, uses (1.0, 0.01). r0 is the unperturbed tally result (reference response value), e0 is the absolute standard deviation of the response. The default 0.01 is therefore an absolute one-sigma uncertainty.
- Returns:
SDFData object containing the SERPENT sensitivity data
- Return type:
SDFData
- Raises:
ValueError – If the specified response is not found or file lists don’t match
kika.sensitivities.sdf
- kika.sensitivities.sdf.sensitivity_to_plot_data(pert_energies, sensitivity, error=None, zaid: int = None, mt: int = None, nuclide: str = None, reaction_name: str = None, per_lethargy: bool = True, uncertainty: bool = True, sigma: float = 1.0, uncertainty_style: str = 'errorbar', label: str = None, **styling_kwargs) MultigroupCrossSectionPlotData | Tuple[MultigroupCrossSectionPlotData, UncertaintyBand][source]
Build PlotData objects from raw sensitivity arrays.
Shared core behind
SDFReactionData.to_plot_data(); usable directly on plain arrays (e.g. the dicts returned bykika.benchmarks.database.BenchmarksDatabase.get_profile_vector()) so both SDF objects and benchmark profiles render through the same code path.Produces a
MultigroupCrossSectionPlotDatastep plot and, when uncertainty is True and per-group absolute standard deviations are available, anUncertaintyBand, both suitable forPlotBuilder.- Parameters:
pert_energies – Energy bin boundaries (n+1 values, ascending, MeV).
sensitivity – Per-group sensitivity coefficients (n values).
error – Per-group absolute standard deviations (n values). If
None(or uncertainty is False) no uncertainty band is returned.zaid – ZAID, used for the plot metadata and the default label.
mt – MT reaction number, used for metadata and the default label.
nuclide – Nuclide symbol for the default label (e.g.
"Fe-56").reaction_name – Reaction label for the default label (e.g.
"(n,el)").per_lethargy – Normalise by the lethargy width of each bin (default True).
uncertainty – Return an
UncertaintyBandwhen error data is present.sigma – Sigma multiplier for the uncertainty band.
uncertainty_style –
'errorbar'(default) or'band'.label – Legend label; auto-generated from nuclide/reaction when None.
styling_kwargs – Forwarded to
MultigroupCrossSectionPlotData.
- Returns:
MultigroupCrossSectionPlotDataalone when no uncertainty band is produced, otherwise(MultigroupCrossSectionPlotData, UncertaintyBand).
- class kika.sensitivities.sdf.SDFReactionData(zaid: int, mt: int, sensitivity: List[float], error: List[float], reaction_name: str | None = None, unit: int | None = None, region: int | None = None)[source]
Bases:
objectContainer for sensitivity data for a specific nuclide and reaction.
- Variables:
zaid – ZAID of the nuclide
mt – MT reaction number
sensitivity – List of sensitivity coefficients
error – List of absolute one-sigma standard deviations
nuclide – Nuclide symbol (calculated from ZAID)
reaction_name – Reaction name (calculated from MT)
- zaid: int
- mt: int
- nuclide: str
- classmethod from_relative_errors(*, zaid: int, mt: int, sensitivity, relative_error, reaction_name: str | None = None, unit: int | None = None, region: int | None = None) SDFReactionData[source]
Build reaction data from relative one-sigma errors.
- property relative_error: List[float]
Return the relative standard deviation for each sensitivity group.
- to_plot_data(pert_energies, per_lethargy: bool = True, uncertainty: bool = True, sigma: float = 1.0, uncertainty_style: str = 'errorbar', label: str = None, **styling_kwargs) MultigroupCrossSectionPlotData | Tuple[MultigroupCrossSectionPlotData, UncertaintyBand][source]
Convert sensitivity data for this reaction into PlotData objects.
Returns a
MultigroupCrossSectionPlotData(step plot) and, optionally, anUncertaintyBandsuitable forPlotBuilder.- Parameters:
pert_energies (array-like) – Energy bin boundaries (n+1 values, ascending order in MeV).
per_lethargy (bool) – If True, normalise sensitivity values by the lethargy width of each bin (matches
Coefficients.plot()behaviour).uncertainty (bool) – If True, return an
UncertaintyBandalongside the nominal data.sigma (float) – Sigma multiplier for the uncertainty band.
uncertainty_style (str) – Rendering style for the uncertainty band:
'errorbar'(default for sensitivity data) or'band'.label (str, optional) – Legend label. Auto-generated as
"<nuclide> <reaction_name>"(e.g."Fe-56 (n,el)") when None.styling_kwargs – Forwarded to
MultigroupCrossSectionPlotData(color,linestyle,linewidth, etc.).
- Returns:
MultigroupCrossSectionPlotDatawhen uncertainty=False, or(MultigroupCrossSectionPlotData, UncertaintyBand)when uncertainty=True.- Return type:
MultigroupCrossSectionPlotData or Tuple[MultigroupCrossSectionPlotData, UncertaintyBand]
- class kika.sensitivities.sdf.SDFData(title: str, energy: str, pert_energies: ~typing.List[float], r0: float = None, e0: float = None, data: ~typing.List[~kika.sensitivities.sdf.SDFReactionData] = <factory>)[source]
Bases:
objectContainer for SDF data.
- Variables:
title – Title of the SDF dataset
energy – Energy value or label
pert_energies – List of perturbation energy boundaries
r0 – Unperturbed tally result (reference response value)
e0 – Absolute one-sigma uncertainty of the unperturbed tally result
data – List of reaction-specific sensitivity data
- title: str
- energy: str
- r0: float = None
- e0: float = None
- data: List[SDFReactionData]
- property relative_response_error: float | None
Return the relative response uncertainty
e0 / abs(r0).
- to_sensitivity_profile() SensitivityProfile[source]
Return the system-total data as a format-neutral sensitivity profile.
SDF entries with non-zero
unitorregionidentify auxiliary mixture/region profiles and are deliberately excluded from UQ vectors.
- to_plot_data(index: int = None, zaid: int = None, mt: int = None, per_lethargy: bool = True, uncertainty: bool = True, sigma: float = 1.0, uncertainty_style: str = 'errorbar', label: str = None, **styling_kwargs) MultigroupCrossSectionPlotData | Tuple[MultigroupCrossSectionPlotData, UncertaintyBand][source]
Convert a reaction’s sensitivity data into PlotData objects.
Look up a reaction either by index into
dataor by (zaid, mt) pair, then delegate toSDFReactionData.to_plot_data().- Parameters:
index (int, optional) – Direct index into
self.data.zaid (int, optional) – ZAID of the nuclide (requires mt as well).
mt (int, optional) – MT reaction number (requires zaid as well).
per_lethargy (bool) – Normalise by lethargy width (default
True).uncertainty (bool) – Include an
UncertaintyBand(defaultTrue).sigma (float) – Sigma multiplier for the uncertainty band.
uncertainty_style (str) – Rendering style for the uncertainty band:
'errorbar'(default for sensitivity data) or'band'.label (str, optional) – Legend label (auto-generated if None).
styling_kwargs – Forwarded to
MultigroupCrossSectionPlotData.
- Returns:
See
SDFReactionData.to_plot_data().- Return type:
MultigroupCrossSectionPlotData or Tuple[MultigroupCrossSectionPlotData, UncertaintyBand]
- Raises:
ValueError – If neither index nor (zaid, mt) is given, or if the requested reaction is not found.
- classmethod merge(sdf_list: List[SDFData], title: str | None = None, energy: str | None = None, r0: float | None = None, e0: float | None = None) SDFData[source]
Merge multiple SDFData objects into a single one.
All SDFs must share the same perturbation energy grid. The merged object contains every
SDFReactionDataentry from the inputs; duplicate(zaid, mt)pairs are not allowed.- Parameters:
sdf_list (List[SDFData]) – List of SDFData objects to combine.
title (Optional[str]) – Override title. If None, uses the common title when all inputs match, otherwise joins distinct titles with
" + ".energy (Optional[str]) – Override energy label. If None, uses the common label when all inputs match, otherwise raises
ValueError.r0 (Optional[float]) – Override response value. If None, uses the common value when all inputs agree, otherwise raises
ValueError.e0 (Optional[float]) – Override absolute response uncertainty. If None, uses the common value when all inputs agree, otherwise raises
ValueError.
- Returns:
A new merged SDFData instance.
- Return type:
SDFData
- Raises:
ValueError – If sdf_list is empty, energy grids differ, r0/e0 values conflict (and none was given), energy labels differ (and none was given), or duplicate (zaid, mt) pairs are found.
- classmethod can_merge(sdf_list: List[SDFData], energy: str | None = None, r0: float | None = None, e0: float | None = None) Tuple[bool, str][source]
Check whether a list of SDFData objects can be merged.
Runs the same validation as
merge()but never raises. Pass the same override parameters you would pass tomerge()to check whether the merge would succeed with those overrides.- Parameters:
- Returns:
(True, "")if the merge would succeed, or(False, reason)with a human-readable explanation otherwise.- Return type:
- write_file(output_dir: str | None = None)[source]
Write the SDF data using the standard SCALE uncertainty convention.
- Parameters:
output_dir (Optional[str]) – Directory where the SDF file will be written. If None, uses current directory.
- group_inelastic_reactions(replace: bool = False, remove_originals: bool = True) None[source]
Group inelastic reactions (MT 51-91) into MT 4 for each nuclide.
This method combines all inelastic scattering reactions (MT 51-91) into the total inelastic scattering reaction (MT 4) for each nuclide.
- Parameters:
- Raises:
ValueError – If MT 4 already exists for a nuclide and replace=False
kika.sensitivities.profile
SensitivityProfile and SensitivityReaction are the validated,
format-neutral inputs used by UQ calculations. Their energy unit is explicit
and reaction uncertainties are absolute one-sigma standard deviations.
Format-neutral sensitivity profiles used by UQ calculations.
- class kika.sensitivities.profile.SensitivityReaction(zaid: int, mt: int, sensitivity: ndarray, uncertainty: ndarray | None = None, label: str | None = None)[source]
Bases:
objectOne format-neutral multigroup sensitivity profile.
- zaid: int
- mt: int
- sensitivity: ndarray
- class kika.sensitivities.profile.SensitivityProfile(energy_grid: ~numpy.ndarray, reactions: ~typing.Tuple[~kika.sensitivities.profile.SensitivityReaction, ...], energy_unit: ~typing.Literal['eV', 'MeV'] = 'MeV', response: float | None = None, response_uncertainty: float | None = None, label: str | None = None, metadata: ~typing.Mapping[str, ~typing.Any] = <factory>)[source]
Bases:
objectValidated sensitivity data independent of SDF or database storage.
Sensitivities are dimensionless relative coefficients.
uncertaintyis the absolute one-sigma uncertainty on each sensitivity coefficient.- energy_grid: ndarray
- reactions: Tuple[SensitivityReaction, ...]
- energy_unit: Literal['eV', 'MeV'] = 'MeV'
- property n_groups: int
kika.sensitivities.condensation
Sensitivity condensation is explicit and format-neutral. Exact condensation requires every target boundary to be present in the source grid; non-nested projection is deliberately rejected. The returned report records the boundary mapping, uncertainty assumption and integral-conservation diagnostic.
Explicit, format-neutral condensation of multigroup sensitivities.
- exception kika.sensitivities.condensation.CondensationError[source]
Bases:
ValueErrorRaised when a sensitivity profile cannot be condensed exactly.
- class kika.sensitivities.condensation.CondensationReport(source_groups: int, target_groups: int, source_energy_grid: Tuple[float, ...], target_energy_grid: Tuple[float, ...], source_energy_unit: Literal['eV', 'MeV'], target_energy_unit: Literal['eV', 'MeV'], boundary_indices: Tuple[int, ...], energy_rtol: float, uncertainty_method: str, assumptions: Tuple[str, ...], max_integral_drift: float)[source]
Bases:
objectDiagnostics and assumptions for one exact condensation operation.
- source_groups: int
- target_groups: int
- source_energy_unit: Literal['eV', 'MeV']
- target_energy_unit: Literal['eV', 'MeV']
- energy_rtol: float
- uncertainty_method: str
- max_integral_drift: float
- class kika.sensitivities.condensation.CondensationResult(profile: SensitivityProfile, operator: ndarray, report: CondensationReport)[source]
Bases:
objectA condensed profile together with its operator and diagnostics.
- profile: SensitivityProfile
- operator: ndarray
- report: CondensationReport
- kika.sensitivities.condensation.condense_sensitivity_profile(profile: SensitivityProfile, target_grid: Iterable[float], *, target_energy_unit: Literal['eV', 'MeV'] | None = None, energy_rtol: float = 1e-05) CondensationResult[source]
Condense a sensitivity profile onto an exactly nested coarser grid.
Group-wise sensitivity coefficients are integral contributions, so source groups inside each target group are summed. Absolute one-sigma statistical uncertainties are combined in quadrature, which assumes independent source- group estimates. Unknown uncertainties remain unknown.
The operation is deliberately strict: the target grid must span the same range and every target boundary must be present in the source grid after explicit unit conversion. Non-nested grid projection is not performed.
- Parameters:
profile – Validated, format-neutral source profile.
target_grid – Ascending boundaries for the coarser output grid.
target_energy_unit – Unit of
target_gridand of the returned profile. Defaults to the source profile unit.energy_rtol – Relative tolerance used only to identify physically equal boundaries. The default covers the six-digit boundary rounding used by DICE SDFs.