kika.input

The input module provides functionality for working with MCNP input files.

Submodules

kika.mcnp.input

class kika.mcnp.input.Input(perturbation: Perturbation = None, materials: MaterialCollection = None)[source]

Bases: object

Main class for storing MCNP input data.

Variables:
  • perturbation – Container for all perturbation cards in the input

  • materials – Container for all material cards in the input

perturbation: Perturbation = None
materials: MaterialCollection = None

kika.mcnp.parse_input

kika.mcnp.parse_input.read_mcnp(file_path, pert_metadata=None)[source]

Reads and parses an MCNP input file.

This function reads an MCNP input file and parses its contents, focusing on PERT cards and material definitions. It creates an Input object containing all parsed data.

Parameters:
  • file_path (str) – Path to the MCNP input file

  • 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 range [start_pert, end_pert].

Returns:

An Input object containing all parsed data

Return type:

Input

kika.mcnp.pert_generator

kika.mcnp.pert_generator.perturb_material(materials: MaterialCollection, material_id: int, nuclide: int | str, density: float | None = None, pert_mat_id: int | None = None, in_place: bool = True, fraction_type: str | None = None) → MaterialCollection | Material[source]

Creates a perturbed material with 100% increase in the specified nuclide’s fraction.

Creates a new material with a 100% increase in the fraction of the specified nuclide. The perturbation is applied after normalizing the original material composition.

Parameters:
  • materials (MaterialCollection) – The material collection containing the material to perturb.

  • material_id (int) – Material ID number to be perturbed.

  • nuclide (int or str) – ZAID (int, e.g., 26056) or symbol (str, e.g., ‘Fe56’) of the nuclide to perturb.

  • density (float, optional) – Density of the original material. If positive, interpreted as atoms/barn-cm, if negative, interpreted as g/cm³. Used for density recalculation info. If None, density calculations are skipped.

  • pert_mat_id (int, optional) – ID for the perturbed material. If None, uses material_id * 100 + 1.

  • in_place (bool, optional) – If True, adds the perturbed material to the existing collection. If False, returns a new MaterialCollection with both original and perturbed materials. Default is True.

  • fraction_type (str, optional) – Output fraction type: ‘atomic’/’ao’ or ‘weight’/’wo’. If None, uses the same format as the original material.

Returns:

If in_place is True, returns the perturbed Material (collection is modified). If in_place is False, returns a new MaterialCollection containing original and perturbed.

Return type:

MaterialCollection or Material

Raises:

ValueError – If the material or nuclide is not found.

Examples

>>> # Modify collection in place
>>> perturbed = kika.perturb_material(input_data.materials, 1007, 'Fe56')
>>>
>>> # Create new collection without modifying original
>>> new_collection = kika.perturb_material(input_data.materials, 1007, 26056, in_place=False)
kika.mcnp.pert_generator.generate_pert_cards(inputfile, cell, reactions, material, energies=None, energy_range=None, density=None, order=2, errors=False, in_place=True, nuclide=None, pert_material=None, pert_density=None)[source]

Generate PERT cards for MCNP sensitivity analysis.

Creates PERT cards based on the provided parameters for first and/or second order perturbation calculations. The density (RHO) value is obtained from the material’s density attribute in the input file.

Can handle multiple materials by providing lists for cell, density, and material parameters. When lists are provided, all list parameters must have the same length as the materials list. The reactions and energies parameters are applied uniformly to all materials.

Parameters:
  • inputfile (str or Path) – Path to the MCNP input file. The file must contain the material definitions with density information for the specified material(s).

  • cell (int, str, list[int], or list[list[int]]) – Cell number(s) for PERT card application. Can be: - Single cell: 3 or '3' - Multiple cells for one material: [3, 5, 7] - Multiple materials: [[3, 5], [7, 9]] (one list per material)

  • reactions (list[int]) – Reaction MT numbers to perturb. Common values: - 1: total cross-section - 2: elastic scattering - 4: inelastic scattering - 18: fission - 51-91: discrete inelastic levels - 102: radiative capture (n,γ)

  • material (int, str, or list) – Material identifier(s) for perturbation. Must exist in the input file. Can be single value or list for multiple materials.

  • energies (array-like, optional) – Energy bin boundaries in eV, must be in ascending order. Used in consecutive pairs to define energy bins. If None, ERG keyword is omitted (energy-integrated). Built-in grids available via kika.energy_grids (e.g., SCALE44, VITAMINJ175).

  • energy_range (tuple of (float or None, float or None), optional) – Filters energies to only include boundaries within the range [min, max]. Either bound can be None to leave it open. For example, energy_range=(0.05, None) keeps boundaries >= 0.05 MeV. Ignored if energies is None. Raises ValueError if filtering leaves fewer than 2 boundaries.

  • density (float or list[float], optional) – Override density value(s) for RHO in PERT cards. If None (default), uses the density from the material definition in the input file. Following MCNP convention: - Negative value: mass density in g/cm³ - Positive value: atomic density in atoms/barn-cm

  • order (int or list[int], optional) – Perturbation order (default: 2): - 1: First-order only (METHOD=2) - 2: First and second order (METHOD=2 and METHOD=3)

  • errors (bool, optional) – If True, include exact error method cards (METHOD=-2, -3, 1). These are typically negligible and computationally expensive. Default is False.

  • in_place (bool, optional) – If True (default), append PERT cards to the original input file. If False, create a new file with suffix _pert_cards.

  • pert_material (int, list[int], optional) – Perturbed material ID(s) used for MAT= in PERT cards. When using multi-material mode this should be the ID of the perturbed material (e.g. 41 instead of 400000). If None in single-material mode, falls back to using material for backward compatibility.

  • pert_density (float, list[float], optional) – Perturbed density used for RHO= in PERT cards. When using multi-material mode this should be the recalculated density of the perturbed material. If None, falls back to the resolved original density for backward compatibility.

Returns:

PERT cards are written to the file.

Return type:

None

Raises:

ValueError – If energies are not in ascending order, if list parameters have inconsistent lengths, if list-of-lists is provided for reactions/energies, or if material density is not available and not provided.

Notes

The RHO parameter in MCNP PERT cards represents the material density, not a perturbation magnitude. MCNP uses this density along with the perturbed material composition to calculate sensitivity coefficients.

Examples

>>> # Basic usage with single material
>>> kika.generate_pert_cards(
...     inputfile='input.i',
...     cell=[3, 5, 7],
...     reactions=[1, 2, 102],
...     material=100701,
...     energies=kika.energy_grids.SCALE44
... )
>>> # Multiple materials with different cells
>>> kika.generate_pert_cards(
...     inputfile='input.i',
...     cell=[[3, 5], [7, 9]],
...     reactions=[1, 2, 102],
...     material=[100701, 100801],
...     energies=kika.energy_grids.SCALE44
... )

See also

perturb_material

Create perturbed material compositions for sensitivity analysis.

compute_sensitivity

Compute sensitivity coefficients from MCNP output.

kika.mcnp.pert_generator.perturb_materials(materials: MaterialCollection, material_ids: List[int], nuclide: int | str, density: float | List[float] | None = None, pert_mat_id: int | List[int] | None = None, **kwargs) → List[Material][source]

Creates perturbed materials for multiple material IDs containing the same nuclide.

Calls perturb_material() for each material ID in the list.

Parameters:
  • materials (MaterialCollection) – The material collection containing the materials to perturb.

  • material_ids (list of int) – Material ID numbers to perturb.

  • nuclide (int or str) – ZAID (int) or symbol (str) of the nuclide to perturb.

  • density (float or list of float, optional) – Density for each material. If a single float, used for all materials. If a list, must match the length of material_ids.

  • pert_mat_id (int or list of int, optional) – Perturbed material ID(s). If a single int, used for all materials. If a list, must match the length of material_ids. If None, defaults are assigned by perturb_material().

  • **kwargs – Additional keyword arguments forwarded to perturb_material() (e.g., in_place, fraction_type).

Returns:

List of perturbed Material objects, one per material ID.

Return type:

list of Material

Raises:

ValueError – If density or pert_mat_id are lists whose length does not match material_ids.

kika.mcnp.pert_generator.generate_PERTcards(inputfile, cell, reactions, material, energies=None, energy_range=None, density=None, order=2, errors=False, in_place=True, nuclide=None, pert_material=None, pert_density=None)

Generate PERT cards for MCNP sensitivity analysis.

Creates PERT cards based on the provided parameters for first and/or second order perturbation calculations. The density (RHO) value is obtained from the material’s density attribute in the input file.

Can handle multiple materials by providing lists for cell, density, and material parameters. When lists are provided, all list parameters must have the same length as the materials list. The reactions and energies parameters are applied uniformly to all materials.

Parameters:
  • inputfile (str or Path) – Path to the MCNP input file. The file must contain the material definitions with density information for the specified material(s).

  • cell (int, str, list[int], or list[list[int]]) – Cell number(s) for PERT card application. Can be: - Single cell: 3 or '3' - Multiple cells for one material: [3, 5, 7] - Multiple materials: [[3, 5], [7, 9]] (one list per material)

  • reactions (list[int]) – Reaction MT numbers to perturb. Common values: - 1: total cross-section - 2: elastic scattering - 4: inelastic scattering - 18: fission - 51-91: discrete inelastic levels - 102: radiative capture (n,γ)

  • material (int, str, or list) – Material identifier(s) for perturbation. Must exist in the input file. Can be single value or list for multiple materials.

  • energies (array-like, optional) – Energy bin boundaries in eV, must be in ascending order. Used in consecutive pairs to define energy bins. If None, ERG keyword is omitted (energy-integrated). Built-in grids available via kika.energy_grids (e.g., SCALE44, VITAMINJ175).

  • energy_range (tuple of (float or None, float or None), optional) – Filters energies to only include boundaries within the range [min, max]. Either bound can be None to leave it open. For example, energy_range=(0.05, None) keeps boundaries >= 0.05 MeV. Ignored if energies is None. Raises ValueError if filtering leaves fewer than 2 boundaries.

  • density (float or list[float], optional) – Override density value(s) for RHO in PERT cards. If None (default), uses the density from the material definition in the input file. Following MCNP convention: - Negative value: mass density in g/cm³ - Positive value: atomic density in atoms/barn-cm

  • order (int or list[int], optional) – Perturbation order (default: 2): - 1: First-order only (METHOD=2) - 2: First and second order (METHOD=2 and METHOD=3)

  • errors (bool, optional) – If True, include exact error method cards (METHOD=-2, -3, 1). These are typically negligible and computationally expensive. Default is False.

  • in_place (bool, optional) – If True (default), append PERT cards to the original input file. If False, create a new file with suffix _pert_cards.

  • pert_material (int, list[int], optional) – Perturbed material ID(s) used for MAT= in PERT cards. When using multi-material mode this should be the ID of the perturbed material (e.g. 41 instead of 400000). If None in single-material mode, falls back to using material for backward compatibility.

  • pert_density (float, list[float], optional) – Perturbed density used for RHO= in PERT cards. When using multi-material mode this should be the recalculated density of the perturbed material. If None, falls back to the resolved original density for backward compatibility.

Returns:

PERT cards are written to the file.

Return type:

None

Raises:

ValueError – If energies are not in ascending order, if list parameters have inconsistent lengths, if list-of-lists is provided for reactions/energies, or if material density is not available and not provided.

Notes

The RHO parameter in MCNP PERT cards represents the material density, not a perturbation magnitude. MCNP uses this density along with the perturbed material composition to calculate sensitivity coefficients.

Examples

>>> # Basic usage with single material
>>> kika.generate_pert_cards(
...     inputfile='input.i',
...     cell=[3, 5, 7],
...     reactions=[1, 2, 102],
...     material=100701,
...     energies=kika.energy_grids.SCALE44
... )
>>> # Multiple materials with different cells
>>> kika.generate_pert_cards(
...     inputfile='input.i',
...     cell=[[3, 5], [7, 9]],
...     reactions=[1, 2, 102],
...     material=[100701, 100801],
...     energies=kika.energy_grids.SCALE44
... )

See also

perturb_material

Create perturbed material compositions for sensitivity analysis.

compute_sensitivity

Compute sensitivity coefficients from MCNP output.

kika.mcnp.material

Backwards-compatible re-export shim for materials module.

This module re-exports material classes from the new kika.materials module to maintain backwards compatibility with existing code that imports from kika.mcnp.material.

The material classes have been moved to kika.materials for multi-code support. New code should import directly from kika.materials instead.

Examples

>>> # Legacy import (still works)
>>> from kika.mcnp.material import Material, MaterialCollection
>>> # Recommended new import
>>> from kika.materials import Material, MaterialCollection
class kika.mcnp.material.Nuclide(zaid: int, fraction: float, libs: ~typing.Dict[str, str] = <factory>)[source]

Bases: object

Lightweight nuclide entry for a material.

zaid

ZAID identifier (e.g. 92235 for U-235).

Type:

int

fraction

Composition fraction stored as a positive value; interpretation is driven by the parent Material.fraction_type.

Type:

float

libs

Per-nuclide library overrides keyed by library keyword (e.g. 'nlib', 'plib').

Type:

dict

convert_natural_element() → None[source]

Print an isotopic breakdown of a natural element.

Raises:

ValueError – If zaid does not represent a natural element or if abundance data are missing.

property element: str | None
property is_natural: bool
property symbol: str

Return the element-mass symbol (e.g., ‘Fe56’, ‘U235’).

zaid: int
fraction: float
libs: Dict[str, str]
class kika.mcnp.material.NuclideAccessor(nuclide_dict: Dict[str, Nuclide])[source]

Bases: object

Dictionary-like accessor that allows retrieving nuclides by ZAID or symbol.

This wrapper allows accessing nuclides using either: - Symbol (str): e.g., ‘Fe56’, ‘U235’, ‘Fe’ (natural) - ZAID (int): e.g., 26056, 92235, 26000 (natural)

String symbols are normalized through ZAID conversion for consistency, so ‘Fe’, ‘fe’, and 26000 all map to the same nuclide.

Examples

>>> material.nuclide['Fe56']  # Access by symbol
>>> material.nuclide[26056]    # Access by ZAID
>>> material.nuclide['Fe']     # Access natural Fe
>>> material.nuclide[26000]    # Access natural Fe by ZAID
get(key: str | int, default=None)[source]

Get nuclide by symbol or ZAID with optional default.

items()[source]

Return view of (symbol, nuclide) pairs.

keys()[source]

Return view of nuclide symbols.

values()[source]

Return view of nuclide objects.

class kika.mcnp.material.Material(id: int, nuclide: ~typing.Dict[str, ~kika.materials.material.Nuclide] | ~kika.materials.material.NuclideAccessor = <factory>, libs: ~typing.Dict[str, str] = <factory>, name: str | None = None, fraction_type: str = 'ao', density: float | None = None, density_unit: str | None = None, temperature: float | None = None, metadata: ~typing.Dict[str, ~typing.Any] = <factory>)[source]

Bases: object

General-purpose material representation.

Fractions are stored as non-negative numbers; fraction_type records whether they represent atomic ('ao') or weight ('wo') fractions. This class provides methods for managing nuclide composition, density, and metadata for a material.

Parameters:
  • id (int) – Material identifier number.

  • nuclide (dict, optional) – Mapping of ZAID to Nuclide objects.

  • libs (dict, optional) – Default library keywords (e.g. 'nlib'). Nuclide libraries override these defaults.

  • name (str, optional) – Optional descriptive name.

  • fraction_type (str, optional) – 'ao' for atomic fractions or 'wo' for weight fractions.

  • density (float, optional) – Density magnitude paired with density_unit.

  • density_unit (str, optional) – Density unit ('g/cc' or 'kg/m3').

  • temperature (float, optional) – Material temperature if available in Kelvin.

  • metadata (dict, optional) – Arbitrary metadata tags.

add_element(element: str, fraction: float, fraction_type: str = 'ao', library: str | None = None) → None[source]

Add a natural element to the material.

This method is a convenience for adding natural elements by symbol only (without mass number). For specific isotopes, use add_nuclide().

Parameters:
  • element (str) – Element symbol (e.g., ‘Fe’, ‘U’, ‘O’). Will be converted to natural ZAID (mass number = 0, e.g., ‘Fe’ -> 26000).

  • fraction (float) – Fraction value; the absolute value is stored and interpreted according to the provided fraction_type.

  • fraction_type (str, optional) – Fraction type: 'ao' for atomic fractions or 'wo' for weight fractions. Default is 'ao'.

  • library (str, optional) – MCNP library suffix (e.g. '80c', '70c', '12p').

Return type:

None

Raises:

ValueError – If element is not a recognized element symbol.

Examples

>>> mat = Material(id=1)
>>> mat.add_element('Fe', 1.0, 'ao')      # Add natural Fe with atomic fraction
>>> mat.add_element('O', 2.0, 'wo')       # Add natural O with weight fraction
add_nuclide(nuclide: int | str, fraction: float, fraction_type: str, library: str | None = None) → None[source]

Add or update a nuclide in the material.

Parameters:
  • nuclide (int or str) – ZAID identifier (int, e.g. 92235) or element-mass symbol (str, e.g. ‘U235’, ‘Fe56’). For natural elements, use symbol without mass number (e.g. ‘Fe’ -> 26000).

  • fraction (float) – Fraction value; the absolute value is stored and interpreted according to the provided fraction_type.

  • fraction_type (str) – Fraction type for this addition: 'ao' for atomic fractions or 'wo' for weight fractions. This updates the material’s fraction_type.

  • library (str, optional) – MCNP library suffix (e.g. '80c', '70c', '12p'). The library type (neutron, photon, or thermal) is automatically inferred from the suffix: ‘c’ -> neutron (nlib), ‘p’ -> photon (plib), ‘y’ -> thermal (ylib). This provides a nuclide-level library override.

Return type:

None

Raises:

ValueError – If nuclide is a string and does not represent a valid element symbol.

Examples

>>> mat = Material(id=1)
>>> mat.add_nuclide('U235', 1.0, 'ao')  # Add U-235 as atomic fraction
>>> mat.add_nuclide(92238, 0.5, 'ao')   # Add U-238 using ZAID
>>> mat.add_nuclide('Fe', 1.0, 'ao')    # Add natural Fe (26000)
clear_nuclides() → None[source]

Remove all nuclides from the material.

Return type:

None

convert_density(unit: str) → None[source]

Convert density in-place to the requested unit.

Parameters:

unit (str) – Target unit string (‘g/cc’ or ‘kg/m3’).

Return type:

None

copy(new_id: int) → Material[source]

Create an exact copy of this material with a new ID.

Parameters:

new_id (int) – Material ID for the new copy.

Returns:

New material instance with all properties copied.

Return type:

Material

density: float | None = None
density_in(unit: str) → float[source]

Return the current density expressed in a different unit.

Parameters:

unit (str) – Target unit string (‘g/cc’ or ‘kg/m3’).

Returns:

Density value in the requested unit.

Return type:

float

Raises:

ValueError – If density is not set or unit is unsupported.

density_unit: str | None = None
property density_with_units: str | None

Return density formatted with units for display.

Returns:

e.g., “10.97 g/cc” or None if not set.

Return type:

str or None

expand_natural_elements(elements: str | List[str] | None = None) → Material[source]

Expand natural elements into isotopic composition using abundance data.

Parameters:

elements (str or list[str], optional) – Specific natural element symbol(s) to expand (e.g., ‘Fe’, ‘C’). If None, all natural elements in the material are expanded.

Returns:

Self reference for chaining.

Return type:

Material

Raises:

ValueError – If a requested element is missing, not natural, or lacks abundance data.

fraction_type: str = 'ao'
get_effective_library(nuclide: int | str, lib_key: str = 'nlib') → str | None[source]

Return the effective MCNP library for a given nuclide.

Parameters:
  • nuclide (int or str) – ZAID identifier or symbol.

  • lib_key (str, optional) – Library keyword to query (e.g. 'nlib', 'plib', 'ylib').

Returns:

Nuclide-level override if present, otherwise the material default.

Return type:

str or None

property is_atomic: bool
property is_weight: bool
name: str | None = None
normalize(fraction_type: str = 'ao') → Material[source]

Normalize all fractions so they sum to 1.0.

This method first converts all fractions to the specified fraction_type (atomic or weight), then rescales them proportionally so that the total sum equals 1.0. This is useful after manually adding nuclides with arbitrary fractional values, such as defining water as H with fraction 2.0 and O with fraction 1.0, then normalizing.

Parameters:

fraction_type (str, optional) – Target fraction type for normalization: 'ao' for atomic fractions or 'wo' for weight fractions. Default is 'ao'.

Returns:

Self reference for chaining.

Return type:

Material

Raises:

ValueError – If total fraction sum is zero or negative, or if fraction_type is invalid.

Examples

>>> mat = Material(id=1)
>>> mat.add_nuclide('H', 2.0, 'ao')
>>> mat.add_nuclide('O', 1.0, 'ao')
>>> mat.normalize('ao')  # Normalize to atomic fractions (default)
>>> mat.normalize('wo')  # Or normalize to weight fractions
remove_library(lib_key: str) → None[source]

Remove a material-level library setting.

Parameters:

lib_key (str) – Library keyword to remove (e.g., ‘nlib’, ‘plib’, ‘ylib’).

Return type:

None

remove_nuclide(nuclide: int | str) → None[source]

Remove a nuclide from the material.

Parameters:

nuclide (int or str) – ZAID identifier or symbol of the nuclide to remove.

Return type:

None

Raises:

KeyError – If the nuclide is not found in the material.

set_density(density: float, unit: str) → None[source]

Set the material density with explicit units.

Parameters:
  • density (float) – Density magnitude.

  • unit (str) – Unit string ('g/cc' or 'kg/m3'); case-insensitive.

Return type:

None

set_id(new_id: int) → None[source]

Change the material ID.

Parameters:

new_id (int) – New material ID.

Return type:

None

set_library(lib_key: str, lib_value: str) → None[source]

Set a material-level library default.

Parameters:
  • lib_key (str) – Library keyword (e.g., ‘nlib’, ‘plib’, ‘ylib’).

  • lib_value (str) – Library suffix value (e.g., ‘80c’, ‘12p’).

Return type:

None

set_name(name: str | None) → None[source]

Set or change the material name.

Parameters:

name (str or None) – New name for the material, or None to clear.

Return type:

None

set_temperature(temperature: float) → None[source]

Set the material temperature in Kelvin.

Parameters:

temperature (float) – Temperature in Kelvin.

Return type:

None

temperature: float | None = None
to_atomic_fraction() → Material[source]

Convert weight fractions to atomic fractions (stored as positives).

Returns:

Self reference for chaining.

Return type:

Material

to_integer_fractions(precision: int = 6) → Material[source]

Convert fractions to integer ratios (inverse of normalize).

This method converts normalized fractions back to integer ratios using rational number approximation. For example, water with normalized atomic fractions (H: 0.6667, O: 0.3333) becomes (H: 2, O: 1).

Parameters:

precision (int, optional) – Maximum denominator for the rational approximation. Higher values give more accurate results but may produce larger integers. Default is 6 (max denominator of 10^6).

Returns:

Self reference for chaining.

Return type:

Material

Notes

  • Works for both atomic and weight fractions (fractions are just numbers).

  • Results are approximate due to float precision.

  • The fractions will still sum to an integer total, not necessarily 1.0.

Examples

>>> mat = Material(id=1)
>>> mat.add_nuclide('H', 0.6667, 'ao')
>>> mat.add_nuclide('O', 0.3333, 'ao')
>>> mat.to_integer_fractions()
>>> # H: 2.0, O: 1.0
to_mcnp() → str[source]

Serialise the material as an MCNP m card.

The output includes MCNP comments with: - Material name (if set) as a comment before the material card - Density in both g/cc and atoms/b-cm (if set) as a comment after libraries - Nuclide symbol after each fraction line

Returns:

MCNP material card formatted as a multi-line string.

Return type:

str

to_serpent() → str[source]

Serialise the material as a Serpent material card.

Serpent format:

mat <name> <density> [rgb R G B] [tmp <T>] [moder <lib> <ZA>]
    <zaid>.<lib> <fraction>

The material name is used if set, otherwise 'mat<id>'. Density uses negative values for mass density (g/cc) and positive for atomic density (atoms/b-cm), following Serpent convention.

Returns:

Serpent material card formatted as a multi-line string.

Return type:

str

to_weight_fraction() → Material[source]

Convert atomic fractions to weight fractions (stored as positives).

Returns:

Self reference for chaining.

Return type:

Material

update_nuclide_fraction(nuclide: int | str, fraction: float) → None[source]

Update the fraction of an existing nuclide.

Parameters:
  • nuclide (int or str) – ZAID identifier or symbol of the nuclide to update.

  • fraction (float) – New fraction value (absolute value will be used).

Return type:

None

Raises:

KeyError – If the nuclide is not found in the material.

id: int
nuclide: Dict[str, Nuclide] | NuclideAccessor
libs: Dict[str, str]
metadata: Dict[str, Any]
class kika.mcnp.material.MaterialCollection(by_id: ~typing.Dict[int, ~kika.materials.material.Material] = <factory>)[source]

Bases: object

Container class for material objects.

add_material(material: Material) → None[source]

Add a material to the collection.

Parameters:

material (Material) – Material to add.

Return type:

None

Raises:

ValueError – If a material with the same ID already exists.

property by_name: Dict[str, Material]

Return materials indexed by name.

Useful for Serpent materials which use string identifiers.

Returns:

Materials keyed by their name attribute.

Return type:

dict of str to Material

classmethod from_mcnp(path: str) → MaterialCollection[source]

Create a MaterialCollection from an MCNP input file.

Parameters:

path (str) – Path to MCNP input file.

Returns:

Collection of materials parsed from the file.

Return type:

MaterialCollection

classmethod from_serpent(path: str) → MaterialCollection[source]

Create a MaterialCollection from a Serpent input file.

Parameters:

path (str) – Path to Serpent input file.

Returns:

Collection of materials parsed from the file.

Return type:

MaterialCollection

to_file(filepath: str, material_ids: List[int] | None = None, header: bool = True) → None[source]

Export materials to a new file in MCNP format.

This creates a new file containing only material cards. Use this when you want to export materials separately from a full MCNP input file.

Parameters:
  • filepath (str) – Path to the output file.

  • material_ids (list of int, optional) – Specific material IDs to write. If None, writes all materials.

  • header (bool, optional) – Whether to include KIKA header/footer comments. Default is True.

Return type:

None

Examples

>>> collection.to_file("materials.txt")  # Export all materials
>>> collection.to_file("subset.txt", material_ids=[1, 2, 3])  # Export specific ones
to_mcnp() → str[source]

Serialise all materials as MCNP material cards.

Returns:

All material cards concatenated with newlines.

Return type:

str

to_serpent() → str[source]

Serialise all materials as Serpent material cards.

Returns:

All material cards concatenated with blank lines between them.

Return type:

str

write_to_mcnp(input_filepath: str, output_filepath: str | None = None, material_ids: List[int] | None = None, force_rewrite: bool = False) → List[int][source]

Update materials in an MCNP input file, only modifying those that changed.

This method reads the original file, compares materials, and only updates those that have actually changed. Unchanged materials are left as-is, preserving their original formatting and any comments.

Parameters:
  • input_filepath (str) – Path to the original MCNP input file.

  • output_filepath (str, optional) – Path for the output file. If None, updates the input file in place.

  • material_ids (list of int, optional) – Specific material IDs to consider for update. If None, considers all materials in this collection.

  • force_rewrite (bool, optional) – If True, rewrites all materials from the collection regardless of whether they changed. Default is False (only update changed materials).

Returns:

List of material IDs that were actually updated (changed or added).

Return type:

list of int

Notes

  • Materials that exist in the collection but not in the file will be added at the end of the material cards section.

  • Materials that exist in the file but not in the collection are left unchanged.

  • Only materials that have actually changed (different nuclides, fractions, or libraries) are updated, unless force_rewrite=True.

Examples

>>> # Update in place
>>> updated = collection.write_to_mcnp("input.i")
>>> print(f"Updated materials: {updated}")
>>> # Save to new file
>>> updated = collection.write_to_mcnp("input.i", "input_modified.i")
>>> # Force rewrite all materials
>>> updated = collection.write_to_mcnp("input.i", force_rewrite=True)
write_to_serpent(input_filepath: str, output_filepath: str | None = None) → None[source]

Update materials in a Serpent input file.

Reads the original file, replaces material definitions with updated versions, and preserves all non-material content.

Parameters:
  • input_filepath (str) – Path to the original Serpent input file.

  • output_filepath (str, optional) – Path for the output file. If None, updates the input file in place.

by_id: Dict[int, Material]