f4enix.input.MCNPinput.Input#

class f4enix.input.MCNPinput.Input(cells: dict[str, Card], surfs: dict[str, Card], materials: MatCardsList, transformations: dict[str, Card], other_data: dict[str, Card], tally_keys: list[int], fmesh_keys: list[int], header: str)#

Bases: object

Class representing an MCNP input file.

cells, surfaces, materials and transformations are handled explicitly. All other datacards are treated generically for the moment being. The parsing is built on the numjuggler python module.

Parameters:
  • cells (dict[str, parser.Card]) – cleaned numjuggler cards for each cells in the input. keys are the number of the cells.

  • surfs (dict[str, parser.Card]) – cleaned numjuggler cards for each surface in the input. keys are the number of the surfaces.

  • materials (MatCardsList) – material cards section of the input.

  • transformations (dict[str, parser.Card]) – list of transformation datacards (i.e. TRn)

  • other_data (dict[str, parser.Card]) – list of all remaining datacards that are treated in a generic way

  • tally_keys (list[int]) – ids of the tallies available in the input

  • fmesh_keys (list[int]) – ids of the fmeshes available in the input

  • header (str) – header of the input file

Variables:
  • cells (dict[str, parser.Card]) – cleaned numjuggler cards for each cells in the input. keys are the number of the cells.

  • surfs (dict[str, parser.Card]) – cleaned numjuggler cards for each surface in the input. keys are the number of the surfaces.

  • materials (MatCardsList) – material cards section of the input.

  • transformations (dict[str, parser.Card]) – list of transformation datacards (i.e. TRn)

  • other_data (dict[str, parser.Card]) – list of all remaining datacards that are treated in a generic way

  • tally_keys (list[int]) – ids of the tallies available in the input

  • fmesh_keys (list[int]) – ids of the fmeshes available in the input

  • header (str) – header of the input file

Examples

The most common way to initiliaze an Input object is from a MCNP input file

>>> from f4enix.input.MCNPinput import Input
... # Read the input file
... inp = Input.from_input(inpfile)
>>> inp.cells
... # inp.surfs
{'1': <numjuggler.parser.Card at 0x26535f02a70>,
 '2': <numjuggler.parser.Card at 0x26535f03130>,
 ...
 '128': <numjuggler.parser.Card at 0x26535f48f70>}

The input can be translated to another library and rewritten to a file

>>> from f4enix.input.libmanager import LibManager
... # Initialize a default nuclear data libraries manager
... libmanager = LibManager()
... # Translate the input to another library
... inp.translate('21c', libmanager)
... inp.write(outfile_path)

Retrieve (and possibly modify) different cards in the input

>>> print('Cell number 1:')
... print(inp.get_cells_by_id([1]))
... print('Surfaces number 10 and 20:')
... print(inp.get_surfs_by_id([10, 20]))
... print('All cells with material M1')
... print(inp.get_cells_by_matID(1))
... # use this method only if the previous ones
... # are not enough
... print('Generic way to obtain cards')
... print(inp._get_cards_by_id(['SDEF', 'IMP:N,P'], inp.other_data))
Cell number 1:
{'1': <numjuggler.parser.Card object at 0x0000026535F02A70>}
Surfaces number 10 and 20:
{'10': <numjuggler.parser.Card object at 0x0000026535F491B0>,
'20': <numjuggler.parser.Card object at 0x0000026535F49390>}
All cells with material M1
{'22': <numjuggler.parser.Card object at 0x00000265360E7850>}
Generic way to obtain cards
{'SDEF': <numjuggler.parser.Card object at 0x0000026535F4B190>,
'IMP:N,P': <numjuggler.parser.Card object at 0x0000026535F4A890>}

Extract a subset of cells depending on some condition and from that dump out a minimal working MCNP input that includes all necessary surfaces, transformations and materials.

>>> # --- Extract cells based on material ---
... inp = Input.from_input(inpfile)
... cells_ids = []  # store here the cells to be extracted
... selected_mat = 11
... for key, cell in inp.cells.items():
...     # get the material of the cell using numjuggler API
...     mat = cell._get_value_by_type('mat')
...     if mat == selected_mat:
...         cells_ids.append(key)
... print(cells_ids)
... # extract the cells subset to a file
... inp.extract_cells(cells_ids, 'outfile.i')

Get useful summary of the material section of the input in a pandas.DataFrame object.

>>> from f4enix.input.MCNPinput import Input
... from f4enix.input.libmanager import LibManager
... # Initialize a default nuclear data libraries manager
... libmanager = LibManager(xsdir_file='my_xsdir')
... inp = Input.from_input(inpfile)
... inp.materials.get_info(libmanager, complete=True)
(                              Atom Fraction  Mass Fraction
Material Submaterial Element
m1       1           H             0.021630      -0.019046
         2           C             0.018920      -0.198524
         3           N             0.002060      -0.025207
         4           O             0.027060      -0.378226
         5           Mg            0.001190      -0.025268
...                                     ...            ...
M29      1           Nb            0.000005      -0.000100
                     Co            0.000041      -0.000500
                     Fe            0.055451      -0.648443
M30      1           H             0.063398      -0.112140
                     O             0.031622      -0.887860
[333 rows x 2 columns],
                            Fraction  Sub-Material Fraction          Material Submaterial Element
M24      1           Ag       0.000016               0.000016
                     Al       0.000631               0.000631
                     As       0.000023               0.000023
                     Au       0.000009               0.000009
                     Bi       0.000163               0.000163
...                                ...                    ...
m7       2           O        0.033428               1.000000
m8       1           Be       0.002970               0.034219
...
                     Cu                0.944769
                     Ni                0.021012
m9       1           Be                1.000000
[333 rows x 3 columns])

Methods

__init__(cells, surfs, materials, ...)

Class representing an MCNP input file.

add_F_tally(tally_ID, particles, cells[, ...])

Add a F-tally to the input

add_cell_fill_u(cell, param, param_value[, ...])

Adds a u=/fill= keyword parameter to a cell that doesn't have it.

add_material_to_void_cell(cell, new_mat_id, ...)

Sets a material (and density) to a void cell.

add_stopCard([nps])

This does not append a stop card anymore but simply changes the NPS card.

add_surface(cell, add_surface[, ...])

Adds a surface to cell's definition as union or intersection.

cells_union(cell_num_list[, new_cell_num])

Given a list of cells, it creates a new cell that is the union of the cells in the list, starting from the first cell in the list.

check_range(range[, who])

Check if the provided range is not within the used index, i.e., if the range is free.

delete_fill_cards()

Delete all fill cards from the input cells.

explore_id_ranges_by_plot()

Returns a Figure and Axes object where the cell and surface IDs used in the input are plotted.

extract_cells(cells, outfile[, ...])

given a list of cells, dumps a minimum MCNP working file.

extract_universe(universe, outfile[, ...])

Dumps a minimum MCNP working file that includes all the cells, surfaces, materials and translations of the universe.

find_first_free_id_range(required_size)

Given a required size, it finds the first ID that can accommodate both cell and surface ID ranges.

from_input(inputfile)

Generate an Input object from an MCNP input text file using numjuggler as a parser

get_cells_by_id(ids[, make_copy])

given a list of cells id return a dictionary of such cells

get_cells_by_matID(matID[, deepcopy_flag])

Given a material ID return a dictionary {key, card} of all the cells to which that material is assigned to.

get_cells_summary()

Get a summary of infos for each cell

get_data_cards(ids)

Get a tranformation card or an other data card by its key.

get_densities_range()

Return a DataFrame listing for all material the minimum and maximum density values encountered in the input cells.

get_materials_subset(ids)

given a list of material ids generate a new MatCardsList with the requested subset

get_surfs_by_id(ids)

given a list of surfaces id return a dictionary of such surfaces

get_tally_summary([fmesh])

Get a summary of the tallies defined in the input

hash_cell(cell, hash_id[, new_cell_num, inplace])

Hash a cell to a new cell number and update the hash dictionary.

hash_multiple_cells(hash_dict)

all keys in the hash dict correspond to hash cells to be added to the cells inlcuded in the hash dict value.

merge(other_inp[, ensure_updated_dicts])

Merge the input with another input object

prepare_void_check(surf, nps[, particle])

Prepare the input for a void check: - remove previous SDEF and tallies - set the sphere surface as source, inward, with correct weight - set the NPS card - set void card

remove_sdef()

Remove the SDEF card and related source definition cards from the input.

remove_tallies([tally_ids])

Remove tallies from the input.

remove_u(cell)

given a cell, it removes the universe option from its definition.

renumber([cells, surfs, universes, ...])

Renumber cards of the input files.

replace_cell_material(cell, new_mat_id, ...)

replace_material(new_mat_id, new_density, ...)

Replace a material and density in the input with other values.

scale_densities(factor)

Scale the density values of all cells by the same factor.

set_cell_void(cell)

translate(newlib, libmanager)

Translate the input to another library

update_zaidinfo(lib_manager)

This methods allows to update the in-line comments for every zaids containing additional information

write(outfilepath[, wrap])

write the input to a file

write_blocks(file, wrap, cells_cards, surfs, ...)

Writes F4Enix dicts of cells, surfaces and data cards.

Attributes

cells

Get the cells attribute.

surfs

Get the surfs attribute.

add_F_tally(tally_ID: int, particles: list[str], cells: Sequence[int | str], add_total: bool = False, energies: Sequence[float] | ndarray | None = None, description: str | None = None, multiplier: str | None = None, add_SD: bool = True)#

Add a F-tally to the input

Parameters:
  • tally_ID (int) – tally ID

  • particles (list[str]) – particle to tally

  • cells (list[int | str]) – list of cells to tally. One can also add a string with a complex cell definition, like unions of cells and cells in a universe, e.g. “((1 2 3) < 10)”

  • add_total (bool, optional) – if True adds the total tally, by default False

  • energies (list[float], optional) – list of energies for the tally, by default None

  • description (str, optional) – description of the tally, by default None

  • multiplier (str, optional) – multiplier of the tally, by default None

  • add_SD (bool, optional) – if True adds the SD 1 card, by default True

static add_cell_fill_u(cell: Card, param: str, param_value: int | str, inplace: bool = True) Card#

Adds a u=/fill= keyword parameter to a cell that doesn’t have it.

Parameters:
  • cell (parser.Card) – numjuggler cell card to which the surface will be added

  • param (str) – can be ‘u’ or ‘fill’, it tells the parameter to be added to the cell.

  • param_value (int) – the value of the parameter ‘u’ or ‘fill’ to be added to the cell.

  • inplace (bool) – if False a deepcopy is created. By default is True.

Returns:

numjuggler card of the modified cell

Return type:

parser.Card

static add_material_to_void_cell(cell: Card, new_mat_id: int, new_density: str) None#

Sets a material (and density) to a void cell.

Parameters:
  • cell (parser.Card) – cell to be modified.

  • new_mat_id (int) – id of the new material.

  • new_density (str) – new value for the density (including sign).

add_stopCard(nps: int | float = 10000000.0)#

This does not append a stop card anymore but simply changes the NPS card. If a float is provided, it is converted to an integer.

Parameters:

nps (int | float) – number of particles to simulate. Default 1e7

Return type:

None.

static add_surface(cell: Card, add_surface: int, new_cell_num: int | None = None, mode: str = 'intersect', inplace: bool = True) Card#

Adds a surface to cell’s definition as union or intersection.

Parameters:
  • cell (parser.Card) – numjuggler cell card to which the surface will be added

  • add_surface (int) – the surface number to be added to cell’s definition. It should include the sign.

  • new_cell_num (int, optional) – new number of the cell after the addition of the surface to cell’s definition, by default None. If a new number is specified, the modifications are done on a copy of the original cell, otherwise these are done inplace.

  • mode (str, optional) – can be ‘union’ or ‘intersect’, it tells the operation with which the surface is added to cell’s definition, by default ‘intersect’

  • inplace (bool) – if False a deepcopy is created. By default is True.

Returns:

numjuggler card of the modified cell

Return type:

parser.Card

property cells: dict[str, Card]#

Get the cells attribute.

cells_union(cell_num_list: list[str], new_cell_num: int | None = None) None#

Given a list of cells, it creates a new cell that is the union of the cells in the list, starting from the first cell in the list. The resulting cell will be put in the dict of cells of the input (with the new number if provided), while the old cells will be deleted. If a renumbering was done, the input must be re-read.

Parameters:
  • cell_list (list[parser.Card]) – list of cells to be united

  • new_cell_num (int, optional) – new number of the union cell, by default None (old number is kept).

check_range(range: list[int], who: str = 'cell') bool#

Check if the provided range is not within the used index, i.e., if the range is free. Both cells and surfaces can be checked.

Parameters:
  • range (list[int]) – list of indices to be checked

  • who (str, optional) – either ‘surf’ or ‘cell’, by default ‘cell’

Returns:

True if the provided range is free, False otherwise

Return type:

bool

Raises:

ValueError – only surf or cell are accepted as who

delete_fill_cards() None#

Delete all fill cards from the input cells.

explore_id_ranges_by_plot() tuple[Figure, Axes]#

Returns a Figure and Axes object where the cell and surface IDs used in the input are plotted. Useful for interactive exploration of the used IDs.

Example

>>> from f4enix.input.MCNPinput import Input
... inp = Input.from_input('input.i')
... fig, ax = inp.explore_id_ranges_by_plot()
... fig.show()
extract_cells(cells: list[int], outfile: PathLike | str, renumber_offsets: dict | None = None, keep_universe: bool = True, extract_fillers: bool = True)#

given a list of cells, dumps a minimum MCNP working file.

The file will includes all the requested cells, defined surfaces, materials and translations.

Parameters:
  • cells (list[int]) – desired list of cells

  • outfile (os.PathLike | str) – path to the file where the MCNP input needs to be dumped

  • renumber_offsets (dict, optional) – apply the self.renumber() function to the extracted input. the dict will be passed as keyargs to the function. Default is None.

  • keep_universe (bool) – If True keeps the ‘U=’ key in the cell cards, otherwise that is removed. Default is True.

  • extract_fillers (bool) – if True extract also the cells belonging to a universe that is used in a ‘FILL=’ keyword. This happens recursively. default is True.

extract_universe(universe: int, outfile: PathLike | str, renumber_offsets: dict | None = None, keep_universe: bool = False)#

Dumps a minimum MCNP working file that includes all the cells, surfaces, materials and translations of the universe. The resulting file doesn’t have the universe keyword in the cell definitions

Parameters:
  • universe (int) – universe id to be extracted

  • outfile (os.PathLike | str) – path to the file where the MCNP input needs to be dumped

  • renumber_offsets (dict, optional) – apply the self.renumber() function to the extracted input. the dict will be passed as keyargs to the function. Default is None.

  • keep_universe (bool) – determines if the u=… card should be kept or not in cells’ definitions. Defult is False.

find_first_free_id_range(required_size: int) int#

Given a required size, it finds the first ID that can accommodate both cell and surface ID ranges.

classmethod from_input(inputfile: PathLike | str) Input#

Generate an Input object from an MCNP input text file using numjuggler as a parser

Parameters:

inputfile (os.PathLike | str) – input file

Returns:

Input object

Return type:

Input

get_cells_by_id(ids: Sequence[int | str], make_copy: bool = False) dict[str, Card]#

given a list of cells id return a dictionary of such cells

Parameters:
  • ids (list[int | str]) – cells id to be extracted

  • make_copy (bool) – if True, makes a deepcopy of the cells instead of working on the original ones. Default is False.

Returns:

extracted cells

Return type:

dict

get_cells_by_matID(matID: int | str, deepcopy_flag: bool = True) dict[str, Card]#

Given a material ID return a dictionary {key, card} of all the cells to which that material is assigned to.

The cells that are returned are deepcopies of the original ones.

Parameters:
  • matID (int | str) – material ID to filter the cells

  • deepcopy_flag (bool) – if False, the cells are not copied. Default is True

Returns:

cells to which the material is assigned to

Return type:

dict[int, parser.Card]

get_cells_summary() DataFrame#

Get a summary of infos for each cell

A DataFrame is returned where for each cell is listed the material, density, universe and filler is present.

Returns:

Summary of cells info

Return type:

pd.DataFrame

get_data_cards(ids: list[str] | str) dict[str, Card]#

Get a tranformation card or an other data card by its key.

For the moment, transformation cards mixed with other data cards is not supported.

Parameters:

ids (list[str] | str) – keys of the cards to retrieve

Returns:

retrieved cards

Return type:

dict[str, parser.Card]

get_densities_range() DataFrame#

Return a DataFrame listing for all material the minimum and maximum density values encountered in the input cells.

Returns:

Range of densities used for each material.

Return type:

pd.DataFrame

get_materials_subset(ids: list[str] | str) MatCardsList | Material#

given a list of material ids generate a new MatCardsList with the requested subset

Parameters:

ids (Union(list[str]), str)) – ids of the materials to put into the subset

Returns:

new materials subset. A single material is returned if only one was requested

Return type:

MatCardsList | Material

get_surfs_by_id(ids: list[int]) dict[str, Card]#

given a list of surfaces id return a dictionary of such surfaces

Parameters:

ids (list[int]) – cells id to be extracted

Returns:

extracted surfaces

Return type:

dict

get_tally_summary(fmesh: bool = False) DataFrame#

Get a summary of the tallies defined in the input

Both normal tallies and fmeshes can be requested. For each tally the number, particle, description and multiplier are listed (if available)

Parameters:

fmesh (bool, optional) – if True produced a summary for the fmehses instead of for the normal tallies, by default False

Returns:

summary info on defined tallies

Return type:

pd.DataFrame

static hash_cell(cell: Card, hash_id: int, new_cell_num: int | None = None, inplace: bool = True) Card#

Hash a cell to a new cell number and update the hash dictionary.

Parameters:
  • cell (parser.Card) – numjuggler cell card to be hashed

  • hash_id (int) – id of the hash cell.

  • new_cell_num (int, optional) – new cell number to which the cell will be hashed. By default is None

  • inplace (bool, optional) – if False a deepcopy is created. By default is True.

hash_multiple_cells(hash_dict: dict[int, list[int]]) None#

all keys in the hash dict correspond to hash cells to be added to the cells inlcuded in the hash dict value.

Parameters:

hash_dict (dict[int, list[int]]) – info on the cells to hash and with what

merge(other_inp: Input, ensure_updated_dicts: bool = False) None#

Merge the input with another input object

Parameters:
  • other_inp (Input) – input to be merged

  • ensure_updated_dicts (bool) – if True, the keys of both inputs are updated. This may not be needed in certain applications and can be set to false if it is sure that the keys are already up to date. Default is False.

prepare_void_check(surf: Card, nps: int, particle: str = 'N') None#

Prepare the input for a void check: - remove previous SDEF and tallies - set the sphere surface as source, inward, with correct weight - set the NPS card - set void card

Parameters:
  • surf (parser.Card) – surface card defining the sphere to be used as source.

  • nps (float) – number of particles to be simulated in the void check.

  • particle (str, optional) – particles to be transported, by default “N”

Raises:
  • ValueError – if the provided card is not a surface

  • ValueError – if the provided surface is not a sphere

remove_sdef() None#

Remove the SDEF card and related source definition cards from the input.

remove_tallies(tally_ids: list[int] | None = None) None#

Remove tallies from the input.

Parameters:

tally_ids (list[int]) – list of tally IDs to be removed. Default is None, which means that all tallies will be removed.

static remove_u(cell: Card) None#

given a cell, it removes the universe option from its definition.

Parameters:

cell (parser.Card) – cell from which the universe has to be removed

renumber(cells: int | None = None, surfs: int | None = None, universes: int | None = None, translations: int | None = None, renum_all: int | None = None, update_keys: bool = False) None#

Renumber cards of the input files. Either all cards can be renumbered using the renum_all parameter or onnly a subset between cells, surfs, universes and translations. Materials are not supported for the time being.

Parameters:
  • cells (int, optional) – offset to be used for cells, by default None

  • surfs (int, optional) – offset to be used for surfaces, by default None

  • universes (int, optional) – offset to be used for universes, by default None

  • translations (int, optional) – offset to be used for translations, by default None

  • renum_all (int, optional) – offset to be used for all supported cards, by default None. It will trump all other specified offsets.

  • update_keys (bool, optional) – if True, the keys of the different dictionaries are updated according to the new numbering. This is useful if more operations are needed on the file. If the file will be directly written after renumbering though, this costly operation is unnecessary. Default is False.

replace_material(new_mat_id: int, new_density: str, old_mat_id: int, u_list: list[int] | None = None) None#

Replace a material and density in the input with other values.

Parameters:
  • new_mat_id (int) – id of the new material (0 for void)

  • new_density (str) – new value for the density (including sign)

  • old_mat_id (int) – id of the material to be replaced

  • u_list (list[int]) – change the material only if cells belong to one of the universes in the list. By default is None, all cells are affected.

scale_densities(factor: float) None#

Scale the density values of all cells by the same factor. Void cells are ignored. Resulting density will be equal to original_density*factor

Parameters:

factor (float) – scaling factors for the densities

property surfs: dict[str, Card]#

Get the surfs attribute.

translate(newlib: str | dict, libmanager: LibManager) None#

Translate the input to another library

Parameters:
  • newlib (dict | str) –

    There are a few ways that newlib can be provided:

    1) str (e.g. 31c), the new library to translate to will be the one indicated;

    2) dic (e.g. {‘98c’ : ‘99c’, ‘31c: 32c’}), the new library is determined based on the old library of the zaid

    3) dic (e.g. {‘98c’: [list of zaids], ‘31c’: [list of zaids]}), the new library to be used is explicitly stated depending on the zaidnum.

  • libmanager (libmanager.LibManager) – Library manager for the conversion.

Return type:

None.

update_zaidinfo(lib_manager: LibManager)#

This methods allows to update the in-line comments for every zaids containing additional information

Parameters:

lib_manager (libmanager.LibManager) – Library manager for the conversion.

Return type:

None.

write(outfilepath: PathLike | str, wrap: bool = False) None#

write the input to a file

Parameters:
  • outfilepath (os.PathLike | str) – path to the output file

  • wrap (bool) – if true the text is wrapped at 80 char. May cause slowdowns

static write_blocks(file: PathLike, wrap: bool, cells_cards: dict[str, Card], surfs: dict[str, Card], materials: MatCardsList, header: list[str] | None = None, trans: dict[str, Card] | None = None, other_data: dict[str, Card] | None = None)#

Writes F4Enix dicts of cells, surfaces and data cards. The method receives cells, surfaces, materials F4Enix dicts and optionally header, transformation and other data F4Enix dicts and prints the MCNP input

Parameters:
  • file (os.PathLike) – path of the MCNP input that will be printed

  • wrap (bool) – flag to check if the input should be wrapped to 80 characters per line

  • cells_cards (dict[str, parser.Card]) – F4Enix dict of cells

  • surfs (dict[str, parser.Card]) – F4Enix dict of surfaces

  • materials (MatCardsList) – MatCardsList object including the materials objects to be printed

  • header (list[str], optional) – list of lines of header of MCNP input, by default None

  • trans (dict[str, parser.Card], optional) – F4Enix dict of transformations, by default None

  • other_data (dict[str, parser.Card], optional) – fEnix dict of MCNP data cards, by default None