armi.utils package¶
Generic ARMI utilities
-
armi.utils.coverageReportHelper(config, dataPaths)[source]¶ Small utility function to generate converage reports.
This was created to side-step the difficulties in submitting multi-line python commands on-the-fly.
-
armi.utils.getFileSHA1Hash(filePath, digits=40)[source]¶ Generate a SHA-1 hash of the input file.
- Parameters
filePath (str) – Path to file to obtain the SHA-1 hash
digits (int, optional) – Number of digits to include in the hash (40 digit maximum for SHA-1)
-
armi.utils.efmt(a)[source]¶ Converts string exponential number to another string with just 2 digits in the exponent.
-
armi.utils.fixThreeDigitExp(strToFloat)[source]¶ Convert FORTRAN numbers that cannot be converted into floats.
Notes
Converts a number line “9.03231714805651-101” (no e or E) to “9.03231714805651e-101”. Some external depletion kernels currently need this fix. From contact with developer: The notation like 1.0-101 is a FORTRAN thing, with history going back to the 60’s. They will only put E before an exponent 99 and below. Fortran will also read these guys just fine, and they are valid floating point numbers. It would not be a useful effort, in terms of time, trying to get FORTRAN to behave differently. The approach has been to write a routine in the reading code which will interpret these.
-
armi.utils.findClosest(listToSearch, val, indx=False)[source]¶ find closest item in a list.
- Parameters
listToSearch (list) – The list to search through
val (float) – The target value that is being searched for in the list
indx (bool, optional) – If true, returns minVal and minIndex, otherwise, just the value
- Returns
minVal (float) – The item in the listToSearch that is closest to val
minI (int) – The index of the item in listToSearch that is closest to val. Returned if indx=True.
-
armi.utils.cleanPath(path)[source]¶ Recursively delete a path.
!!! careful with this !!! It can delete the entire cluster.
We add copious os.path.exists checks in case an MPI set of things is trying to delete everything at the same time. Always check filenames for some special flag when calling this, especially with full permissions on the cluster. You could accidentally delete everyone’s work with one misplaced line! This doesn’t ask questions.
Safety nets include a whitelist of paths.
This makes use of shutil.rmtree and os.remove
- Returns
success – True if file was deleted. False if it was not.
- Return type
bool
-
armi.utils.copyWithoutBlocking(src, dest)[source]¶ Copy a file in a separate thread to avoid blocking while IO completes.
Useful for copying large files while ARMI moves along.
-
armi.utils.linearInterpolation(x0, y0, x1, y1, targetX=None, targetY=None)[source]¶ does a linear interpolation (or extrapolation) for y=f(x)
- Parameters
x0,y0,x1,y1 (float) – Coordinates of two points to interpolate between
targetX (float, optional) – X value to evaluate the line at
targetY (float, optional) – Y value we want to find the x value for (inverse interpolation)
- Returns
interpY (float) – The value of y(targetX), if targetX is not None
interpX (float) – The value of x where y(x) = targetY (if targetY is not None)
y = m(x-x0) + b
x = (y-b)/m
-
armi.utils.parabolaFromPoints(p1, p2, p3)[source]¶ find the parabola that passes through three points
We solve a simultaneous equation with three points.
- A = x1**2 x1 1
x2**2 x2 1 x3**2 x3 1
- b = y1
y2 y3
find coefficients Ax=b
- Parameters
p1 (tuple) – first point (x,y) coordinates
p2,p3 (tuple, second and third points.) –
- Returns
- Return type
a,b,c coefficients of y=ax^2+bx+c
-
armi.utils.parabolicInterpolation(ap, bp, cp, targetY)[source]¶ Given parabola coefficients, this interpolates the time that would give k=targetK.
keff = at^2+bt+c We want to solve a*t^2+bt+c-targetK = 0.0 for time. if there are real roots, we should probably take the smallest one because the larger one might be at very high burnup. If there are no real roots, just take the point where the deriv ==0, or 2at+b=0, so t = -b/2a The slope of the curve is the solution to 2at+b at whatever t has been determined
- Parameters
bp,cp (ap,) – coefficients of a parabola y = ap*x^2 + bp*x + cp
targetK (float) – The keff to find the cycle length of
- Returns
realRoots – (root, slope) The best guess of the cycle length that will give k=targetK If no positive root was found, this is the maximum of the curve. In that case, it will be a negative number. If there are two positive roots, there will be two entries.
- slopefloat
The slope of the keff vs. time curve at t=newTime
- Return type
list of tuples
-
armi.utils.getFloat(val)[source]¶ returns float version of val, or None if it’s impossible. Useful for converting user-input into floats when ‘’ might be possible.
-
armi.utils.getTimeStepNum(cycleNumber, subcycleNumber, cs)[source]¶ Return the timestep associated with cycle and tn.
- Parameters
cycleNumber (int, The cycle number) –
subcycleNumber (int, The intra-cycle time node (0 for BOC, etc.)) –
cs (Settings object) –
-
armi.utils.getCycleNode(timeStepNum, cs)[source]¶ Return the (cycle, node) corresponding to a cumulative time step number.
- Parameters
timeStepNum – The cumulative number of time steps since the beginning
cs – A case Settings object to get the nodes-per-cycle from
-
armi.utils.getNodesPerCycle(cs)[source]¶ Return the number of nodes per cycles for this case settings.
-
armi.utils.getPreviousTimeStep(cycle, node, burnSteps)[source]¶ Return the time step before the specified time step
-
armi.utils.tryPickleOnAllContents(obj, ignore=None, path=None, verbose=False)[source]¶ Attempts to pickle all members of this object and identifies those who cannot be pickled.
Useful for debugging MPI-bcast errors
Not recursive yet. Would be nice to have it loop through nested objects (blocks in assems in reactors)
- Parameters
obj (object) – Any object to be tested.
ignore (iterable) – list of string variable names to ignore.
path (str) – the path in which to test pickle.
verbose (bool, optional) – Print all objects whether they fail or not
-
armi.utils.doTestPickleOnAllContents2(obj, ignore=None, path=None, verbose=False)[source]¶ Attempts to find one unpickleable object in a nested object
- Returns
pickleChain – list of names in a chain that are unpickleable. Just one example per object e.g. [‘r’,’assemblies’,’A101’,’lib] means the lib is unpicklable.
- Return type
list
-
class
armi.utils.MyPickler[source]¶ Bases:
_pickle.PicklerThe big guns. This will find your pickle errors if all else fails.
Use with tryPickleOnAllContents3.
-
armi.utils.tryPickleOnAllContents3(obj, ignore=None, path=None, verbose=False)[source]¶ Definitely find pickle errors
Notes
In this form, this just finds one pickle error and then crashes. If you want to make it work like the other testPickle functions and handle errors, you could. But usually you just have to find one unpickleable SOB.
-
armi.utils.classesInHierarchy(obj, classCounts, visited=None)[source]¶ Count the number of instances of each class contained in an objects heirarchy.
-
armi.utils.slantSplit(val, ratio, nodes, order='low first')[source]¶ Returns a list of values who’s sum is equal to the value specified. The ratio between the highest and lowest value is equal to the specified ratio, and the middle values trend linearly between them.
-
armi.utils.newtonsMethod(func, goal, guess, maxIterations=None, cs=None, positiveGuesses=False)[source]¶ Solves a Newton’s method with the given function, goal value, and first guess.
- Parameters
func (function) – The function that guess will be changed to try to make it return the goal value.
goal (float) – The function will be changed until it’s return equals this value.
guess (float) – The first guess value to do Newton’s method on the func.
maxIterations (int) – The maximum number of iterations that the Newton’s method will be allowed to perform.
- Returns
ans – The guess that when input to the func returns the goal.
- Return type
float
-
armi.utils.minimizeScalarFunc(func, goal, guess, maxIterations=None, cs=None, positiveGuesses=False, method=None, tol=0.001)[source]¶ Use scipy minimize with the given function, goal value, and first guess.
- Parameters
func (function) – The function that guess will be changed to try to make it return the goal value.
goal (float) – The function will be changed until it’s return equals this value.
guess (float) – The first guess value to do Newton’s method on the func.
maxIterations (int) – The maximum number of iterations that the Newton’s method will be allowed to perform.
- Returns
ans – The guess that when input to the func returns the goal.
- Return type
float
-
armi.utils.runFunctionFromAllModules(funcName, *args, **kwargs)[source]¶ Runs funcName on all modules of ARMI, if it exists.
- Parameters
funcName (str) – The function to run if it is found in a module.
**kwargs (*args,) –
Notes
This imports all modules in ARMI, and if you have a script that isn’t inside a
if __name__=='__main__', you will be in trouble.This could also be useful for finding input consistency checkers for the GUI.
See also
armi.settings.addAllDefaultSettings()gets all the settings from all modules
-
armi.utils.mkdir(dirname)[source]¶ Keeps trying to make a directory, outputting whatever errors it encounters, until it is successful.
- Parameters
dirname (str) – Path to the directory to create. What you would normally pass to os.mkdir.
-
armi.utils.prependToList(originalList, listToPrepend)[source]¶ Add a new list to the beginnning of an original list.
- Parameters
originalList (list) – The list to prepend to.
listToPrepend (list) – The list to add to the beginning of (prepend) the originalList.
- Returns
originalList – The original list with the listToPrepend at it’s beginning.
- Return type
list
-
armi.utils.capStrLen(string, length)[source]¶ Truncates a string to a certain length.
Adds ‘…’ if it’s too long.
- Parameters
string (str) – The string to cap at length l.
length (int) – The maximum length of the string s.
-
armi.utils.list2str(strings, width=None, preStrings=None, fmt=None)[source]¶ Turn a list of strings into one string, applying the specified format to each.
- Parameters
strings (list) – The items to create centered strings in the line for. Can be str, float, int, etc.
width (int, optional) – The maximum width that the strings are allowed to take up. Only strings are affected by this parameter, because it does not make sense to truncate ints or floats.
preStrings (list of str, optional) – Any strings that come before the centered strings.
fmt (str, optional) – The format to apply to each string, such as ‘ >4d’, ‘^12.4E’.
-
armi.utils.createFormattedStrWithDelimiter(dataList, maxNumberOfValuesBeforeDelimiter=9, delimiter='\n')[source]¶ Return a formatted string with delimiters from a list of data.
- Parameters
dataList (list) – List of data that will be formatted into a string
maxNumberOfValuesBeforeDelimiter (int) – maximum number of values to have before the delimiter is added
delimiter (str) – A delimiter on the formatted string (default: “n”)
Notes
As an example:
>>> createFormattedStrWithDelimiter(['hello', 'world', '1', '2', '3', '4'], ... maxNumberOfValuesBeforeDelimiter=3, delimiter = '\n') "hello, world, 1, \n2, 3, \n4, 5\n"
-
armi.utils.rotateXY(x, y, degreesCounterclockwise=None, radiansCounterclockwise=None)[source]¶ Rotates x, y coordinates
- Parameters
y (x,) – coordinates
degreesCounterclockwise (float) – Degrees to rotate in the CCW direction
radiansCounterclockwise (float) – Radians to rotate in the CCW direction
- Returns
xr, yr – the rotated coordinates.
- Return type
array_like
-
armi.utils.convertToSlice(x, increment=False)[source]¶ Convert a int, float, list of ints or floats, None, or slice to a slice. Also optionally increments that slice to make it easy to line up lists that don’t start with 0.
Use this with numpy.array (numpy.ndarray) types to easily get selections of it’s elements.
- Parameters
x (multiple types allowed.) – int: select one index. list of int: select these index numbers. None: select all indices. slice: select this slice
- Returns
slice – Returns a slice object that can be used in an array like a[x] to select from its members. Also, the slice has its index numbers decremented by 1. It can also return a numpy array, which can be used to slice other numpy arrays in the same way as a slice.
- Return type
slice
Examples
a = numpy.array([10, 11, 12, 13])
>>> convertToSlice(2) slice(2, 3, None) >>> a[convertToSlice(2)] array([12])
>>> convertToSlice(2, increment=-1) slice(1, 2, None) >>> a[convertToSlice(2, increment=-1)] array([11])
>>> a[convertToSlice(None)] array([10, 11, 12, 13])
>>> a[utils.convertToSlice([1, 3])] array([11, 13])
>>> a[utils.convertToSlice([1, 3], increment=-1)] array([10, 12])
>>> a[utils.convertToSlice(slice(2, 3, None), increment=-1)] array([11])
-
armi.utils.plotMatrix(matrix, fName, minV=None, maxV=None, show=False, title=None, xlabel=None, ylabel=None, xticks=None, yticks=None, cmap=None, figsize=None)[source]¶ Plots a matrix
-
armi.utils.userName()[source]¶ Return a database-friendly username.
This will return the current user’s username, removing any prefix like
pre-, if present.Notes
ARMI uses the user name in a number of places, namely in the database names, which cannot contain hyphens.
-
armi.utils.expandRepeatedFloats(repeatedList)[source]¶ Return an expanded repeat list.
Notes
R char is valid for showing the number of repeats in MCNP. For examples the list: [150, 200, ‘9R’] indicates a 150 day cycle followed by 10 200 day cycles.
-
armi.utils.getStepsFromValues(values, prevValue=0.0)[source]¶ Convert list of floats to list of steps between each float.
-
armi.utils.average1DWithinTolerance(vals, tolerance=0.2)[source]¶ Compute the average of a series of arrays with a tolerance.
Tuned for averaging assembly meshes or block heights.
- vals2D numpy.array
could be assembly x axial mesh tops or heights
-
armi.utils.findNearestValue(searchList, searchValue)[source]¶ Search a given list for the value that is closest to the given search value.
-
armi.utils.findNearestValueAndIndex(searchList, searchValue)[source]¶ Search a given list for the value that is closest to the given search value. Return a tuple containing the value and its index in the list.
-
class
armi.utils.MergeableDict[source]¶ Bases:
dictOverrides python dictionary and implements a merge method.
Notes
Allows multiple dictionaries to be combined in a single line
-
armi.utils.safeCopy(src, dst)[source]¶ This copy overwrites
shutil.copyand checks that copy operation is truly completed before continuing.
Submodules¶
- armi.utils.asciimaps module
- armi.utils.codeTiming module
- armi.utils.densityTools module
- armi.utils.directoryChangers module
- armi.utils.directoryChangersMpi module
- armi.utils.dynamicImporter module
- armi.utils.flags module
- armi.utils.hexagon module
- armi.utils.iterables module
- armi.utils.outputCache module
- armi.utils.parsing module
- armi.utils.pathTools module
- armi.utils.plotting module
- armi.utils.properties module
- armi.utils.textProcessors module
- armi.utils.triangle module
- armi.utils.units module