Skip to content

Commit

Permalink
Reorganizing Math Utilities (#584)
Browse files Browse the repository at this point in the history
  • Loading branch information
john-science authored Feb 23, 2022
1 parent a3d78a9 commit 53d64ab
Show file tree
Hide file tree
Showing 19 changed files with 814 additions and 868 deletions.
6 changes: 3 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# How to contribute

The ARMI framework project strongly encourages developers to help contribute to and build the code.
The ARMI framework project strongly encourages developers to help contribute to the codebase.

The ARMI framework code is open source, and your contributions will become open source.
Although fewer laws apply to open source materials because they are publicly-available, you still
Expand All @@ -13,16 +13,16 @@ There are a lot of things we need help with right off the bat, to get your feet
* Many more type annotations are desired. Type issues cause lots of bugs.
* Fewer Pylint warnings
* Better documentation
* Additional relevance to thermal reactors
* Better test coverage
* Targeted speedups (e.g. informed by a profiler)
* Additional relevance to thermal reactors

Naturally, we encourage other kinds of contributions as well.

## Testing

Any contribution must pass all included unit tests. The tests are built and run with the
pytest system. Please add new tests if you add new functionality. You can generally just run
`pytest` system. Please add new tests if you add new functionality. You can generally just run
`tox` to build the testing environment and execute all the tests and pylint checks.

## Submitting changes
Expand Down
2 changes: 1 addition & 1 deletion armi/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@
import collections

from armi import plugins, pluginManager, meta, settings
from armi.reactor import parameters
from armi.settings import Setting
from armi.settings import fwSettings
from armi.reactor import parameters


class App:
Expand Down
10 changes: 5 additions & 5 deletions armi/bookkeeping/report/reportingUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,12 @@

import armi
from armi import runLog
from armi import utils
from armi.utils import getFileSHA1Hash
from armi.utils import iterables
from armi.utils import units
from armi.utils import textProcessors
from armi.utils import plotting
from armi.utils.mathematics import findClosest
from armi import interfaces
from armi.bookkeeping import report
from armi.reactor.flags import Flags
Expand Down Expand Up @@ -131,7 +132,7 @@ def _listInputFiles(cs):
shaHash = (
"MISSING"
if (not fName or not os.path.exists(fName))
else utils.getFileSHA1Hash(fName, digits=10)
else getFileSHA1Hash(fName, digits=10)
)
inputInfo.append((label, fName, shaHash))

Expand Down Expand Up @@ -649,9 +650,8 @@ def summarizeZones(core, cs):
peakAssem = highPow[peakIndex]

avgPFrac = sum(pFracList) / len(pFracList) # true mean power fraction
_avgAssemPFrac, avgIndex = utils.findClosest(
pFracList, avgPFrac, indx=True
) # the closest-to-average pfrac in the list
# the closest-to-average pfrac in the list
_avgAssemPFrac, avgIndex = findClosest(pFracList, avgPFrac, indx=True)
avgAssem = highPow[avgIndex] # the actual average assembly

# ok, now need counts, and peak and avg. flow and power in high power region.
Expand Down
1 change: 0 additions & 1 deletion armi/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@


def pytest_sessionstart(session):

print("Initializing generic ARMI Framework application")
configure(apps.App())
bootstrapArmiTestEnv()
Expand Down
4 changes: 2 additions & 2 deletions armi/materials/lithium.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
"""

from armi import runLog
from armi import utils
from armi.materials import material
from armi.nucDirectory import nuclideBases as nb
from armi.utils.mathematics import getFloat


class Lithium(material.Fluid):
Expand All @@ -46,7 +46,7 @@ def applyInputParams(self, LI_wt_frac=None, LI6_wt_frac=None, *args, **kwargs):

LI6_wt_frac = LI6_wt_frac or LI_wt_frac

enrich = utils.getFloat(LI6_wt_frac)
enrich = getFloat(LI6_wt_frac)
# allow 0.0 to pass in!
if enrich is not None:
self.adjustMassEnrichment(LI6_wt_frac)
Expand Down
6 changes: 2 additions & 4 deletions armi/materials/sulfur.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"""

from armi import runLog
from armi import utils
from armi.utils.mathematics import linearInterpolation
from armi.utils.units import getTk
from armi.materials import material

Expand Down Expand Up @@ -67,6 +67,4 @@ def volumetricExpansion(self, Tk=None, Tc=None):
Tk = getTk(Tc, Tk)

self.checkTempRange(334, 430, Tk, "volumetric expansion")
return utils.linearInterpolation(
x0=334, y0=5.28e-4, x1=430, y1=5.56e-4, targetX=Tk
)
return linearInterpolation(x0=334, y0=5.28e-4, x1=430, y1=5.56e-4, targetX=Tk)
1 change: 1 addition & 0 deletions armi/nucDirectory/nuclideBases.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ def __readMc2Nuclides():
"""
with open(os.path.join(armi.context.RES, "mc2Nuclides.yaml"), "r") as mc2Nucs:
mc2Nuclides = yaml.load(mc2Nucs, Loader=yaml.FullLoader)

# now add the mc2 specific nuclideBases, and correct the mc2Ids when a > 0 and state = 0
for name, data in mc2Nuclides.items():
z = data["z"]
Expand Down
10 changes: 5 additions & 5 deletions armi/operators/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
from armi import context
from armi import runLog
from armi.bookkeeping import memoryProfiler
from armi import utils
from armi.utils.mathematics import expandRepeatedFloats
from armi.utils import codeTiming
from armi.utils import pathTools
from armi import settings
Expand Down Expand Up @@ -142,19 +142,19 @@ def _initFastPath():

def _getCycleLengths(self):
"""Return the cycle length for each cycle of the system as a list."""
return utils.expandRepeatedFloats(self.cs["cycleLengths"]) or (
return expandRepeatedFloats(self.cs["cycleLengths"]) or (
[self.cs["cycleLength"]] * self.cs["nCycles"]
)

def _getAvailabilityFactors(self):
"""Return the availability factors (capacity factor) for each cycle of the system as a list."""
return utils.expandRepeatedFloats(self.cs["availabilityFactors"]) or (
return expandRepeatedFloats(self.cs["availabilityFactors"]) or (
[self.cs["availabilityFactor"]] * self.cs["nCycles"]
)

def _getPowerFractions(self):
"""Return the power fractions for each cycle of the system as a list."""
return utils.expandRepeatedFloats(self.cs["powerFractions"]) or (
return expandRepeatedFloats(self.cs["powerFractions"]) or (
[1.0 for _cl in self.cycleLengths]
)

Expand Down Expand Up @@ -919,7 +919,7 @@ def snapshotRequest(self, cycle, node):
newFolder = "snapShot{0}_{1}".format(cycle, node)
if os.path.exists(newFolder):
runLog.important("Deleting existing snapshot data in {0}".format(newFolder))
utils.pathTools.cleanPath(newFolder) # careful with cleanPath!
pathTools.cleanPath(newFolder) # careful with cleanPath!
# give it a minute.
time.sleep(1)

Expand Down
7 changes: 4 additions & 3 deletions armi/operators/settingsValidation.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import armi
from armi import runLog, settings, utils
from armi.utils import pathTools
from armi.utils.mathematics import expandRepeatedFloats
from armi.reactor import geometry
from armi.reactor import systemLayoutInput
from armi.physics import neutronics
Expand Down Expand Up @@ -463,7 +464,7 @@ def _willBeCopiedFrom(fName):

def _factorsAreValid(factors, maxVal=1.0):
try:
expandedList = utils.expandRepeatedFloats(factors)
expandedList = expandRepeatedFloats(factors)
except (ValueError, IndexError):
return False
return (
Expand Down Expand Up @@ -527,8 +528,8 @@ def _correctCycles():
def decayCyclesHaveInputThatWillBeIgnored():
"""Check if there is any decay-related input that will be ignored."""
try:
powerFracs = utils.expandRepeatedFloats(self.cs["powerFractions"])
availabilities = utils.expandRepeatedFloats(
powerFracs = expandRepeatedFloats(self.cs["powerFractions"])
availabilities = expandRepeatedFloats(
self.cs["availabilityFactors"]
) or ([self.cs["availabilityFactor"]] * self.cs["nCycles"])
except: # pylint: disable=bare-except
Expand Down
12 changes: 5 additions & 7 deletions armi/physics/fuelCycle/fuelHandlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,8 @@
from armi.reactor.flags import Flags
from armi.operators import RunTypes
from armi.utils import directoryChangers, pathTools
from armi import utils
from armi.utils import plotting
from armi.utils.mathematics import resampleStepwise
from armi.utils.mathematics import findClosest, resampleStepwise

runLog = logging.getLogger(__name__)

Expand Down Expand Up @@ -1249,17 +1248,16 @@ def buildRingSchedule(
# build widths
widths = []
for i, ring in enumerate(baseRings[:-1]):
widths.append(
abs(baseRings[i + 1] - ring) - 1
) # 0 is the most restrictive, meaning don't even look in other rings.
# 0 is the most restrictive, meaning don't even look in other rings.
widths.append(abs(baseRings[i + 1] - ring) - 1)
widths.append(0) # add the last ring with width 0.

# step 2: locate which rings should be reversed to give the jump-ring effect.
if jumpRingFrom is not None:
_closestRingFrom, jumpRingFromIndex = utils.findClosest(
_closestRingFrom, jumpRingFromIndex = findClosest(
baseRings, jumpRingFrom, indx=True
)
_closestRingTo, jumpRingToIndex = utils.findClosest(
_closestRingTo, jumpRingToIndex = findClosest(
baseRings, jumpRingTo, indx=True
)
else:
Expand Down
12 changes: 4 additions & 8 deletions armi/physics/neutronics/energyGroups.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@
Energy group structures for multigroup neutronics calculations.
"""

import itertools
import copy
import itertools
import math

import numpy

from armi import utils
from armi import runLog
from armi.utils.mathematics import findNearestValue
from .const import (
FAST_FLUX_THRESHOLD_EV,
MAXIMUM_XS_LIBRARY_ENERGY,
Expand All @@ -32,10 +33,7 @@


def getFastFluxGroupCutoff(eGrpStruc):
"""
Given a constant "fast" energy threshold, return which ARMI energy group index contains this threshold.
"""

"""Given a constant "fast" energy threshold, return which ARMI energy group index contains this threshold."""
gThres = -1
for g, eV in enumerate(eGrpStruc):
if eV < FAST_FLUX_THRESHOLD_EV:
Expand Down Expand Up @@ -302,9 +300,7 @@ def _create_multigroup_structures_on_finegroup_energies(
modifiedEnergyBounds = set()
modifiedEnergyBounds.add(max(finegroup_energy_bounds))
for energyBound in multigroup_energy_bounds[1:]:
modifiedEnergyBounds.add(
utils.findNearestValue(finegroup_energy_bounds, energyBound)
)
modifiedEnergyBounds.add(findNearestValue(finegroup_energy_bounds, energyBound))

return sorted(modifiedEnergyBounds, reverse=True)

Expand Down
4 changes: 2 additions & 2 deletions armi/reactor/converters/uniformMesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
import numpy

from armi import runLog
from armi import utils
from armi.utils.mathematics import average1DWithinTolerance
from armi.utils import iterables
from armi.utils import plotting
from armi.reactor import grids
Expand Down Expand Up @@ -124,7 +124,7 @@ def _computeAverageAxialMesh(self):
aMesh = src.core.findAllAxialMeshPoints([a], applySubMesh=True)[1:]
if len(aMesh) == refNumPoints:
allMeshes.append(aMesh)
self._uniformMesh = utils.average1DWithinTolerance(numpy.array(allMeshes))
self._uniformMesh = average1DWithinTolerance(numpy.array(allMeshes))

@staticmethod
def _createNewAssembly(sourceAssembly):
Expand Down
13 changes: 7 additions & 6 deletions armi/reactor/reactors.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

import numpy

from armi import getPluginManagerOrFail, materials, nuclearDataIO, settings, utils
from armi import getPluginManagerOrFail, materials, nuclearDataIO, settings
from armi.reactor import assemblies
from armi.reactor import assemblyLists
from armi.reactor import composites
Expand All @@ -42,9 +42,10 @@
from armi.reactor import parameters
from armi.reactor import zones
from armi.reactor import reactorParameters
from armi.utils import units
from armi.utils import createFormattedStrWithDelimiter, units
from armi.utils.iterables import Sequence
from armi.utils import directoryChangers
from armi.utils.mathematics import average1DWithinTolerance
from armi.reactor.flags import Flags
from armi.settings.fwSettings.globalSettings import CONF_MATERIAL_NAMESPACE_ORDER
from armi.nuclearDataIO import xsLibraries
Expand Down Expand Up @@ -1305,19 +1306,19 @@ def summarizeNuclideCategories(self):
[
(
"Fuel",
utils.createFormattedStrWithDelimiter(
createFormattedStrWithDelimiter(
self._nuclideCategories["fuel"]
),
),
(
"Coolant",
utils.createFormattedStrWithDelimiter(
createFormattedStrWithDelimiter(
self._nuclideCategories["coolant"]
),
),
(
"Structure",
utils.createFormattedStrWithDelimiter(
createFormattedStrWithDelimiter(
self._nuclideCategories["structure"]
),
),
Expand Down Expand Up @@ -1874,7 +1875,7 @@ def updateAxialMesh(self):
# depending on what makes the most sense
refAssem = self.refAssem
refMesh = self.findAllAxialMeshPoints([refAssem])
avgHeight = utils.average1DWithinTolerance(
avgHeight = average1DWithinTolerance(
numpy.array(
[
[
Expand Down
Loading

0 comments on commit 53d64ab

Please sign in to comment.