mckit_meshes package

Subpackages

Submodules

mckit_meshes.fmesh module

Classes and functions for operations with fmesh tallies.

class mckit_meshes.fmesh.FMesh[source]

Bases: object

Fmesh tally.

Class to load MCNP FMESH output file, process and write in various formats. Processing includes normalization, merging and conversion to weights mesh.

Attrs:
NPZ_MARK: Signature to be stored in the of meta entry in a npz file.

This is used to check that the file is for FMesh object.

NPZ_FORMAT: Identifies version of format of data stored in npz file.

exception FMeshError[source]

Bases: RuntimeError

FMesh class specific exception.

NPZ_FORMAT = np.int16(4)
NPZ_MARK = np.int16(5445)
__init__(name, kind, geometry_spec, ebins, data, errors, totals=None, totals_err=None, comment=None)[source]

Construct FMesh instance object.

Parameters:
Return type:

None

property axis: ndarray

Get axis of a cylinder mesh.

check_attributes()[source]

Check consistency of attributes.

Return type:

None

property comment: str | None

Comment from FC card for this mesh tally.

property e: ndarray

Energy bins.

format_cylinder_origin_and_axis_label()[source]

Format the first string for cylinder mesh.

Return type:

str

property geometry_spec: CartesianGeometrySpec | CylinderGeometrySpec | AbstractGeometrySpec
get_spectrum(x, y, z)[source]

Gets energy spectrum at the specified point.

Parameters:
  • x (float) – X, Y and Z coordinate of the point where energy spectrum is required. If point is located outside the mesh, zeros are returned.

  • y (float) –

  • z (float) –

Return type:

tuple[Union[Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], Union[Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]], Union[Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], complex, bytes, str, _NestedSequence[complex | bytes | str]]] | None

Returns:

ebins, data, err or None

Energy bin boundaries, group energy spectrum and relative errors.

get_totals(*, x=None, y=None, z=None)[source]

Get total values for specified grid points.

If a coordinate is not specified, then all the points along this coordinate.

Parameters:
Return type:

tuple[ndarray, ndarray] | None

Returns:

totals, total_err for the specified coordinates

has_better_precision_than(other)[source]

Compare precision achieved for the meshes.

Parameters:

other (FMesh) – mesh

Return type:

bool

Returns:

True if this mesh is more precise than other one.

property has_multiple_energy_bins: bool

Check if there’s more than 1 energy bin.

If True, then totals and totals err should present.

Returns:

True if there are more than one energy bins.

property ibins: ndarray

Synonym to geometry bins x or R.

property is_cylinder: bool

Is this mesh cylinder?

Note

MCNP uses origin on mesh tally specification, both rectilinear and cylinder, but outputs origin only for cylinder mesh.

Returns:

True if this is a cylinder mesh.

is_equal_by_geometry(other)[source]

Check if the meshes are equivalent by geometry.

Parameters:

other (FMesh) – mesh to compare to

Return type:

bool

Returns:

True, if this mesh is equal to other by geometry, otherwise False

is_equal_by_mesh(other)[source]

Check if the meshes are equivalent by kind and geometry.

Parameters:

other (FMesh) – “FMesh”:

Return type:

bool

Returns:

True, if this mesh is equal to other by kind and geometry, otherwise False

property jbins: ndarray

Synonym to geometry jbins (y or Z).

Returns:

jbins from the geometry spec

property kbins: ndarray

Synonym to geometry kbins (z or Theta).

Returns:

kbins from the geometry spec

classmethod load_npz(_file)[source]

Loads Fmesh object from the binary file.

Parameters:

_file (str | Path) – npz-file to load from.

Return type:

FMesh

Returns:

The loaded FMesh object.

property origin: ndarray

Get origin for cylinder mesh.

rebin(new_x, new_y, new_z, new_name=-1, extra_process_threshold=1000000)[source]

Extract data for a new spatial grid.

Parameters:
  • new_x (ndarray) – A new binning over X axis.

  • new_y (ndarray) – A new binning over Y axis.

  • new_z (ndarray) – A new binning over Z axis.

  • new_name – A name for the rebinned mesh to be created. (Default value = -1)

  • extra_process_threshold (int) – At which size of data use multiple Python processes

Return type:

FMesh

Returns:

New FMesh object with the rebinned data.

rebin_single(new_x, new_y, new_z, new_name=-1)[source]

Create FMesh object corresponding to this one by fluxes, but over new mesh.

Ags:

new_x: A new binning over X axis. new_y: A new binning over Y axis. new_z: A new binning over Z axis. new_name: name for the rebinned mesh to be created.

Return type:

FMesh

Returns:

New FMesh object with the rebinned data.

Parameters:
save2vtk(filename=None, data_name=None)[source]

Saves this fmesh data to vtk file.

Data is saved for every energy bin and, if there are multiple energy bins, for total values (sum across energy axis).

Parameters:
  • filename (str | None) – Name of file to which this object is stored. A .vtk extension will be appended. By default, the name of file is the tally name.

  • data_name (str | None) – Name of data which will appear in vtk file. If None, tally name and type will be used.

Return type:

str

Returns:

Full path to saved VTK file.

save_2_mcnp_mesh(stream)[source]

Saves the mesh in a file in a format similar to mcnp mesh tally textual representation.

Parameters:

stream (TextIO) – stream to store the mesh.

Return type:

None

save_2_npz(filename, check_existing_file_strategy=<function raise_error_when_file_exists_strategy>)[source]

Writes this object to numpy npz file.

Parameters:
  • filename (Path) – Filename to which the object is saved. If file is a file-object, then the filename is unchanged. If file is a string, a .npz extension will be appended to the file name if it does not already have one. By default, the name of file is the tally name.

  • check_existing_file_strategy – what to do if an output file already exists

Return type:

None

select_indexes(*, x=None, y=None, z=None)[source]

Select indexes in spatial bins corresponding to given coordinates.

If coordinate is not specified, then return all the points along this coordinate.

Parameters:
Return type:

tuple[int | slice | ndarray, int | slice | ndarray, int | slice | ndarray]

Returns:

tuple of indexes along the coordinates

shrink(emin=None, emax=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, new_name=-1)[source]

Select subset of e-voxels within given geometry and energy limits.

Parameters:
  • emin – limits for new bins

  • emax – (Default value = None)

  • xmin – (Default value = None)

  • xmax – (Default value = None)

  • ymin – (Default value = None)

  • ymax – (Default value = None)

  • zmin – (Default value = None)

  • zmax – (Default value = None)

  • new_name – name for mesh to be created, default -1.

Return type:

FMesh

Returns:

A new FMesh with reduced bins.

surrounds_point(x, y, z, *, local=True)[source]

Check if a point x,y,z is within the mesh spatial grid.

Parameters:
  • x (float) – point’s coordinate x

  • y (float) – … y

  • z (float) – … z

  • local (bool) – if True the point coordinates are local for the mesh

Return type:

bool

Returns:

True if point is within the mesh’s grid.

total_by_energy(new_name=0)[source]

Integrate over energy bins.

Parameters:

new_name (int) – name for new FMesh (Default value = 0)

Return type:

FMesh

Returns:

The new FMesh object with only one energy bin.

property total_precision: float

Get total precision of this mesh.

Returns:

total precision from totals or errors, if there are no totals.

property totals: ndarray | None

Total values over energy.

property totals_err: ndarray | None

Relative errors of total values over energy.

property vec: ndarray

Get Theta reference direction for cylinder mesh.

mckit_meshes.fmesh.check_ebins(fid, keys)[source]

Check if energy bins present in a mesh tally output values.

If next nonempty line starts with a word keys[0] (i.e. “Energy”), then the energy bins present. Also check that the remaining keys correspond to the nonempty line.

Parameters:
  • fid (Iterable[str]) – text rows to scan, including prepending empty rows

  • keys (list[str]) – sequence of words to check

  • fid – Iterable[str]:

  • keys – List[str]:

Return type:

bool

Returns:

True if energy bins are present, False otherwise.

Raises:

ValueError – if keys don’t correspond to the nonempty line.

mckit_meshes.fmesh.fix_mesh_comment(mesh_no, comment)[source]

Remove digits from an FMESH comment.

MCNP error: prints digits in front of comment when the tally number takes more than 3 digits.

Parameters:
  • mesh_no (int) – mesh tally number

  • comment (str) – … comment

Return type:

str

Returns:

corrected comment

mckit_meshes.fmesh.iter_meshtal(fid, name_select=None, tally_select=None)[source]

Iterates fmesh tallies from fid.

Parameters:
  • fid (TextIO) – A stream to read meshes from.

  • name_select (Callable[[int], bool] | None) – A function returning True, if tally name is acceptable, otherwise skips tally reading and parsing

  • tally_select (Callable[[FMesh], bool] | None) – A function returning True, if total tally content is acceptable

Yields:

Mesh tallies filtered.

Return type:

Generator[FMesh]

mckit_meshes.fmesh.m_2_npz(stream, prefix, *, name_select=<function <lambda>>, tally_select=<function <lambda>>, suffix='', mesh_file_info=None, check_existing_file_strategy=<function raise_error_when_file_exists_strategy>)[source]

Splits the tallies from the mesh file into separate npz files.

Parameters:
  • stream (TextIO) – File with MCNP mesh tallies to read

  • prefix (Path) – Prefix for separate mesh files names

  • name_select – Filter fmesh by names (default: no filter)

  • tally_select – function(FMesh)->bool Filter fmesh by content. (default: no filter)

  • suffix (str) – Prefix for separate mesh files names

  • mesh_file_info – structure to store meshtal file header info: nps.

  • check_existing_file_strategy – what to do if an output file already exists

  • stream – TextIO:

  • prefix – Path:

  • suffix – str: (Default value = “”)

Return type:

int

Returns:

Total number of files created

mckit_meshes.fmesh.merge_tallies(name, kind, *tally_weight, comment=None)[source]

Makes superposition of tallies with specific weights.

Parameters:
  • name (int) – Name of new fmesh tally.

  • kind (int) – Type of new fmesh tally. It can be -1 (or any arbitrary integer).

  • tally_weight (tuple[FMesh, float]) – List of tally-weight pairs (tuples). tally is FMesh instance. weight is float.

  • comment (str | None) – A comment to assign to the new mesh tally

Return type:

FMesh

Returns:

The merged FMesh.

mckit_meshes.fmesh.meshes_to_vtk(*meshes, out_dir=None, get_mesh_description_strategy)[source]

Export FMesh objects to VTK files.

Parameters:
  • meshes (FMesh) – one or more meshes to output

  • out_dir (Path | None) – path to output directory

  • get_mesh_description_strategy (Callable[[FMesh], str]) – strategy to create a mesh description

Return type:

None

mckit_meshes.fmesh.read_meshtal(stream, select=None, mesh_file_info=None)[source]

Reads fmesh tallies from a stream.

Parameters:
  • stream (TextIO) – The text stream to read.

  • select – Selects the meshes actually to process (Default value = None)

  • mesh_file_info – object to collect information from m-file header (Default value = None)

Return type:

list[FMesh]

Returns:

The list of individual fmesh tally.

mckit_meshes.m_file_iterator module

mckit_meshes.m_file_iterator.m_file_iterator(stream)[source]
Return type:

Generator[list[str]]

Parameters:

stream (TextIO)

mckit_meshes.mesh2com module

mckit_meshes.mesh2com.mesh2com(xbins, ybins, zbins, out=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

Prints content for mcnp com file to plot crossections over mesh.

voxels centers and with normals in x, y and z directions.

mckit_meshes.particle_kind module

Particle kinds enumeration and methods.

class mckit_meshes.particle_kind.ParticleKind[source]

Bases: IntEnum

Particle kinds enumeration and methods.

__new__(value)
e = 3
electron = 3
property heating_reactions: str

MCNP specified heating reactions for neutrons and photons.

Returns:

reaction specification for neutron or photon particle

Raises:

ValueError – if there’s no specification for the particle

n = 1
neutron = 1
p = 2
photon = 2
property short: str

One letter synonym for a long name.

Returns:

the fires letter of the name

mckit_meshes.version module

The meta information on the mckit_meshes package.

mckit_meshes.wgtmesh module

Weight mesh class and functions.

class mckit_meshes.wgtmesh.Particles[source]

Bases: IntEnum

Particle kind enum.

__new__(value)
n = 0
neutron = 0
p = 1
photon = 1
class mckit_meshes.wgtmesh.WgtMesh[source]

Bases: object

Class to work with MCNP weight window files.

class MergeSpec[source]

Bases: NamedTuple

MergeSpec(wm, nps)

nps: int

Alias for field number 1

wm: WgtMesh

Alias for field number 0

__init__(geometry_spec, energies, weights)[source]
Parameters:

geometry_spec (CartesianGeometrySpec | CylinderGeometrySpec)

property axs: ndarray | None
bins_are_equal(other)[source]
Return type:

bool

Parameters:

other (WgtMesh)

property count_parts: int
property count_voxels: int
drop_lower_energies(min_energy, part=0)[source]
Return type:

WgtMesh

Parameters:
property energies: list[Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]]
property geometry_spec: CartesianGeometrySpec | CylinderGeometrySpec
get_mean_square_distance_weights(point)[source]
Return type:

WgtMesh

property ibins: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]
invert(normalization_point, normalized_value=1.0)[source]

Get reciprocal of self weights and normalize to 1 at given point.

Important

A caller specifies normalization_point in local coordinates. See GeometrySpec.local_coordinates.

Parameters:
  • normalization_point (ndarray) – Point at which output weights should be 1

  • normalized_value (float) – value which should be set at normalization_point.

Returns:

Normalized reciprocal of self weights.

Return type:

WgtMesh

property is_cylinder: bool
property jbins: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]
property kbins: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]
classmethod merge(*merge_specs)[source]

Combine weight meshes produced from different runs with weighting factor.

Note

Importance of a mesh voxel i is $1/w_i$ and is proportional to average portion $p_i$ of passing particle weight W to a tally, for which the weight mesh is computed. To obtain combined weight on merging two meshes, we will combine the probabilities using weighting factors and use reciprocal of a result as a resulting weight of mesh voxel. The weighting factors are usually NPS (Number particles sampled) from a run on which a mesh was produced.

The combined probability in resulting voxel i is:

\[ \begin{align}\begin{aligned}w_ij - weight in voxel i of mesh j n_j - nps - weighting factor on combining of mesh j\\p_ij = 1/w_ij - probability for voxel i of mesh j\\p_i = \frac{ \sum_j{n_j*p_ij} { \sum_j{n_j} }\end{aligned}\end{align} \]

So, the resulting voxel i weight level is:

\[w_i = \frac{1} {p_i}\]
Parameters:

merge_specs (MergeSpec | tuple[WgtMesh, int]) – iterable of pairs (WgtMesh, nps), where nps is weighting factor

Returns:

merged weights and total nps (or sum of weighting factors)

Return type:

MergeSpec

property neutron_weights: ndarray
normalize(normalization_point, normalized_value=1.0, energy_bin=-1)[source]

Scale weights to have value value at normalisation_point.

All other voxels are scaled proportionally.

Parameters:
  • normalization_point (ndarray) – Coordinates of point where the weights should equal value.

  • normalized_value (float) – The value which should be at normalization_point

  • energy_bin – index of energy bin at which set normalized value, default - the last one.

Return type:

WgtMesh

Returns:

New normalized weights.

property origin: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]
part(particle)[source]
Return type:

tuple[ndarray, ndarray]

Parameters:

particle (Particles)

property photon_weights: ndarray
print_mcnp_generator_spec(io=None, ref='600 0 50', columns=6)[source]
Return type:

None

Parameters:

columns (int)

print_meshtal_spec(io=None, tally_n_number=14, tally_p_number=24, columns=6)[source]
Return type:

None

Parameters:
  • io (TextIO | None)

  • tally_n_number (int)

  • tally_p_number (int)

  • columns (int)

classmethod read(f)[source]

Read an MCNP weights file.

See format description at MCNP User Manual, Version 5 (p.489 or Appendix J, p. J-1)

Parameters:

f (TextIO) – Input file in WWINP format

Returns:

loaded mesh.

Return type:

WgtMesh

reciprocal()[source]

Invert weights values.

To be used for anti-forward method of weight generation.

Return type:

WgtMesh

Returns:

: out:

Reciprocal of this weights

validate()[source]
Return type:

None

property vec: ndarray | None
property weights: list[ndarray]
write(stream)[source]

Writes the mesh to stream.

See WWINP format, MCNP User Manual, Appendix J, Table J.1

Return type:

None

Parameters:

stream (TextIO)

Args;

stream: a stream to write to

mckit_meshes.wgtmesh.ensure_float_arrays(*arrays)[source]
Return type:

Generator[ndarray]

Parameters:

arrays (Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str])

mckit_meshes.wgtmesh.make_geometry_spec(ibins, jbins, kbins, origin=None, axs=None, vec=None)[source]

Make Cartesian or Cylinder geometry specification from with given parameters.

The parameters are converted to numpy arrays.

Parameters:
  • ibins – X or R bins

  • jbins – Y or Z bins

  • kbins – Z or Theta bins

  • origin – origin point

  • axs – Cylinder mesh axis

  • vec – Cylinder mesh angle reference vector

Return type:

CartesianGeometrySpec | CylinderGeometrySpec

Returns:

spec - new geometry specification

mckit_meshes.wgtmesh.parse_coordinates(inp)[source]
Return type:

ndarray

Parameters:

inp (list[str])

mckit_meshes.wgtmesh.prepare_probabilities_and_nps(_nps, _weights)[source]

Computes intermediate data for merging procedure.

The probabilities are reciprocals to weights. Zero weights mean zero probabilities and don’t affect the merged result.

Parameters:
  • _nps (int) – weighting multiplier

  • _weights (ndarray) – weights to convert to probabilities

Return type:

tuple[ndarray, ndarray]

Returns:

normalization factors and probabilities

mckit_meshes.wgtmesh.produce_strings(stream, format_spec)[source]
Return type:

list[str]

mckit_meshes.wgtmesh.reciprocal(a, zero_index=None)[source]
Return type:

ndarray

Parameters:

Module contents

Code to manipulate MCNP weight and tally meshes.