# serpentTools.Detector¶

class serpentTools.Detector(name, bins=None, tallies=None, errors=None, indexes=None, grids=None)

Class for storing detector data with multiple bins

For detectors with spatial meshes, including rectilinear, hexagonal, cylindrical, or spherical meshes, refer to companion classes serpentTools.CartesianDetector, serpentTools.HexagonalDetector, serpentTools.CylindricalDetector, or serpentTools.SphericalDetector

If simply the tally bins are available, it is recommended to use the fromTallyBins() class method. This will reshape the data and separate the mean tally [second to last column] and relative errors [last column].

Parameters
• name (str) – Name of this detector

• bins (numpy.ndarray, optional) – Full 2D tally data from detector file, including tallies and errors in last two columns

• tallies (numpy.ndarray, optional) – Reshaped tally data such that each dimension corresponds to a unique bin, such as energy or spatial bin.

• errors (numpy.ndarray, optional) – Reshaped error data such that each dimension corresponds to a unique bin, such as energy or spatial bin. Note: this is a relative error as it would appear in the output file

• indexes (iterable of string, optional) – Iterable naming the bins that correspond to reshaped tally and errors.

• grids (dict, optional) – Supplemental grids that may be supplied to this detector, including energy points or spatial coordinates.

name

Name of this detector

Type

str

bins

Full 2D tally data from detector file, including tallies and errors in last two columns

Type
tallies

Reshaped tally data such that each dimension corresponds to a unique bin, such as energy or spatial bin.

Type
errors

Reshaped error data such that each dimension corresponds to a unique bin, such as energy or spatial bin. Note: this is a relative error as it would appear in the output file

Type
indexes

Iterable naming the bins that correspond to reshaped tally and errors. The tuple (energy, ymesh, xmesh) indicates that tallies should have three dimensions corresponding to various energy, y-position, and x-position bins. Must be set after tallies or errors and agree with the shape of each

Type
grids

Dictionary containing grid information for binned quantities like energy or time.

Type

dict

energy

Potential underlying energy grid in MeV. Will be (n_ene, 3), where n_ene is the number of values in the energy grid. Each row energy[j] will be the low point, high point, and mid point of the energy bin j.

Type
Raises
• ValueError – If some spatial grid is found in indexes during creation. This class is ill-suited for these problems. Refer to the companion classes mentioned above.

• IndexError – If the shapes of bins, tallies, and errors are inconsistent

compare(other, lower=0, upper=10, sigma=2, verbosity=None)

Compare the results of this reader to another.

For values without uncertainties, the upper and lower arguments control what passes and what messages get raised. If a quantity in other is less than lower percent different that the same quantity on this object, consider this allowable and make no messages. Quantities that are greater than upper percent different will have a error messages printed and the comparison will return False, but continue. Quantities with difference between these ranges will have warning messages printed.

Parameters
• other – Other reader instance against which to compare. Must be a similar class as this one.

• lower (float or int) – Lower limit for relative tolerances in percent Differences below this will be considered allowable

• upper (float or int) – Upper limit for relative tolerances in percent. Differences above this will be considered failure and errors messages will be raised

• sigma (int) – Size of confidence interval to apply to quantities with uncertainties. Quantities that do not have overlapping confidence intervals will fail

• verbosity (None or str) – If given, update the verbosity just for this comparison.

Returns

True if the objects are in agreement with each other according to the parameters specified

Return type

bool

Raises
• TypeError – If other is not of the same class as this class nor a subclass of this class

• ValueError – If upper > lower, If sigma, lower, or upper are negative

classmethod fromTallyBins(name, bins, grids=None)

Create a detector instance from 2D detector data

Parameters
• name (str) – Name of this detector

• bins (numpy.ndarray) – 2D array taken from Serpent. Expected to have either 12 or 13 columns, where the latter indicates a time bin has been added.

• grids (dict, optional) – Dictionary of underlying energy, space, and/or time data.

Returns

Return type

Detector

Raises

ValueError – If the tally data does not appear to be Serpent 2 tally data

meshPlot(xdim, ydim, what='tallies', fixed=None, ax=None, cmap=None, cbarLabel=None, logColor=False, xlabel=None, ylabel=None, logx=False, logy=False, loglog=False, title=None, thresh=None, **kwargs)

Plot tally data as a function of two bin types on a cartesian mesh.

Parameters
• xdim (str) – Primary dimension - will correspond to x-axis on plot

• ydim (str) – Secondary dimension - will correspond to y-axis on plot

• what ({'tallies', 'errors'}) – Color meshes from tally data or uncertainties

• fixed (None or dict) – Dictionary controlling the reduction in data down to one dimension

• ax (matplotlib.axes.Axes, optional) – Ax on which to plot the data. If not provided, create a new plot

• cmap (str, optional) – Valid Matplotlib colormap to apply to the plot.

• logColor (bool) – If true, apply a logarithmic coloring to the data positive data

• xlabel (str or bool, optional) – Label to apply to the x-axis. If given as None, a label will be determined from other arguments. If not None but evaluates to False, do not label.

• ylabel (str or bool, optional) – Label to apply to the y-axis. If given as None, a label will be determined from other arguments. If not None but evaluates to False, do not label.

• logx (bool) – Apply a log scale to x axis.

• logy (bool) – Apply a log scale to y axis.

• loglog (bool) – Apply a log scale to both axes.

• title (str) – Title to apply to the figure.

• thresh (float) – Do not plot data less than or equal to this value.

• cbarLabel (str) – Label to apply to colorbar. If not given, infer from what

• kwargs (dict, optional) – Addition keyword arguments to pass to pcolormesh()

Returns

Ax on which the data was plotted.

Return type

matplotlib.axes.Axes

Raises
• serpentTools.SerpentToolsException – If data to be plotted, with or without constraints, is not 1D

• KeyError – If fixed is given and xdim or ydim are contained in fixed

• AttributeError – If the data set by what not in the allowed selection

• ValueError – If the data contains negative quantities and logColor is True

plot(xdim=None, what='tallies', sigma=None, fixed=None, ax=None, xlabel=None, ylabel=None, steps=False, labels=None, logx=False, logy=False, loglog=False, legend=None, ncol=1, title=None, **kwargs)

Simple plot routine for 1- or 2-D data

Parameters
• xdim (str, optional) – Plot the data corresponding to changing this bin, e.g. "energy". Must exist in indexes

• what ({'tallies', 'errors'}) – Primary data to plot

• sigma (int) – Confidence interval to apply to errors. If not given or 0, no errors will be drawn.

• fixed (None or dict) – Dictionary controlling the reduction in data down to one dimension

• ax (matplotlib.axes.Axes, optional) – Ax on which to plot the data. If not provided, create a new plot

• xlabel (str or bool, optional) – Label to apply to the x-axis. If given as None, a label will be determined from other arguments. If not None but evaluates to False, do not label. If xdim is given and xlabel is None, then xdim will be applied to the x-axis.

• ylabel (str or bool, optional) – Label to apply to the y-axis. If given as None, a label will be determined from other arguments. If not None but evaluates to False, do not label.

• steps (bool) – If true, plot the data as constant inside the respective bins. Sets drawstyle to be steps-post unless drawstyle given in kwargs

• labels (None or iterable) – Labels to apply to each line drawn. This can be used to identify which bin is plotted as what line.

• logx (bool) – Apply a log scale to x axis.

• logy (bool) – Apply a log scale to y axis.

• loglog (bool) – Apply a log scale to both axes.

• legend (bool or str or None) – Automatically label the plot. No legend will be made if a single item is plotted. Pass one of the following values to place the legend outside the plot: above, right

• ncol (int) – Integer number of columns to apply to the legend.

• title (str) – Title to apply to the figure.

• kwargs (dict, optional) – Addition keyword arguments to pass to plot() or errorbar() function.

Returns

Ax on which the data was plotted.

Return type

matplotlib.axes.Axes

Raises

reshapedBins()

Obtain multi-dimensional tally, error, and index data

Returns

• tallies (numpy.ndarray) – Potentially multi-dimensional array corresponding to tally data along each bin index

• errors (numpy.ndarray) – Potentially multi-dimensional array corresponding to tally relative error along each bin index

• indexes (list of str) – Ordering of named bin information, e.g. "xmesh", "energy", corresponding to axis in tallies and errors

Examples

A detector is created with a single bin with two bins values. These could represent tallying two different reaction rates

>>> import numpy
>>> from serpentTools import Detector
>>> bins = numpy.ones((2, 12))
>>> bins[1, 0] = 2
>>> bins[1, 4] = 2
>>> bins[:, -2:] = [
...     [5.0,  0.1],
...     [10.0, 0.2]]
>>> det = Detector("reshape", bins=bins)
>>> tallies, errors, indexes = det.reshapedBins()
>>> tallies
array([5.0, 10.0])
>>> errors
array([0.1, 0.2])
>>> indexes
["reaction", ]

slice(fixed, data='tallies')

Return a view of the reshaped array where certain axes are fixed

Parameters
• fixed (dict) – dictionary to aid in the restriction on the multidimensional array. Keys correspond to the various grids present in indexes while the values are used to

• data ({'tallies', 'errors'}) – Which data set to slice

Returns

View into the respective data where certain dimensions have been removed

Return type

numpy.ndarray

Raises

AttributeError – If data is not supported

spectrumPlot(fixed=None, ax=None, normalize=True, xlabel=None, ylabel=None, steps=True, logx=True, logy=False, loglog=False, sigma=3, labels=None, legend=None, ncol=1, title=None, **kwargs)

Quick plot of the detector value as a function of energy.

Parameters
• fixed (None or dict) – Dictionary controlling the reduction in data

• ax (matplotlib.axes.Axes, optional) – Ax on which to plot the data. If not provided, create a new plot

• normalize (bool) – Normalize quantities per unit lethargy

• xlabel (str or bool, optional) – Label to apply to the x-axis. If given as None, a label will be determined from other arguments. If not None but evaluates to False, do not label.

• ylabel (str or bool, optional) – Label to apply to the y-axis. If given as None, a label will be determined from other arguments. If not None but evaluates to False, do not label.

• steps (bool) – Plot tally as constant inside bin

• logx (bool) – Apply a log scale to x axis.

• logy (bool) – Apply a log scale to y axis.

• loglog (bool) – Apply a log scale to both axes.

• sigma (int) – Confidence interval to apply to errors. If not given or 0, no errors will be drawn.

• labels (None or iterable) – Labels to apply to each line drawn. This can be used to identify which bin is plotted as what line.

• legend (bool or str or None) – Automatically label the plot. No legend will be made if a single item is plotted. Pass one of the following values to place the legend outside the plot: above, right

• ncol (int) – Integer number of columns to apply to the legend.

• title (str) – Title to apply to the figure.

• kwargs (dict, optional) – Addition keyword arguments to pass to matplotlib.pyplot.plot() or matplotlib.pyplot.errorbar()

Returns

Ax on which the data was plotted.

Return type

matplotlib.axes.Axes

Raises

SerpentToolsException – if number of rows in data not equal to number of energy groups

toMatlab(fileP, reconvert=True, append=True, format='5', longNames=True, compress=True, oned='row')

Write a binary MATLAB file from the contents of this object

Parameters
• fileP (str or file-like object) – Name of the file to write. .mat extension is not needed if append==True

• reconvert (bool) – If this evaluates to true, convert values back into their original form as they appear in the output file.

• append (bool) – If true and a file exists under output, append to that file. Otherwise the file will be overwritten

• format ({'5', '4'}) – Format of file to write. '5' for MATLAB 5 to 7.2, '4' for MATLAB 4

• longNames (bool) – If true, allow variable names to reach 63 characters, which works with MATLAB 7.6+. Otherwise, maximum length is 31 characters

• compress (bool) – If true, compress matrices on write

• oned ({'row', 'col'}) – Write one-dimensional arrays as row vectors if oned=='row' (default), or column vectors

Raises

ImportError – If scipy is not installed