Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing a couple of plots to use initial block height #1998

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
18 changes: 13 additions & 5 deletions armi/bookkeeping/report/newReportUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,9 +627,17 @@ def insertCoreAndAssemblyMaps(
generateFullCoreMap : bool, default False
showBlockAxMesh : bool, default True
"""
assemPrototypes = set()
assemPrototypes = []
for aKey in blueprint.assemDesigns.keys():
assemPrototypes.add(blueprint.constructAssem(cs, name=aKey))
a = blueprint.constructAssem(cs, name=aKey)
# since we will be plotting cold input heights, we need to make sure that
# that these new assemblies have access to a blueprints somewhere up the
# composite chain. normally this would happen through an assembly's parent
# reactor, but because these newly created assemblies are in the load queue,
# they will not have a parent reactor. to get around this, we just attach
# the blueprints to the assembly directly.
a.blueprints = blueprint
assemPrototypes.append(a)

counts = {
assemDesign.name: len(r.core.getChildrenOfType(assemDesign.name))
Expand All @@ -647,19 +655,19 @@ def insertCoreAndAssemblyMaps(
report[DESIGN]["Assembly Designs"] = newReports.Section("Assembly Designs")
currentSection = report[DESIGN]["Assembly Designs"]
for plotNum, assemBatch in enumerate(
iterables.chunk(list(assemPrototypes), MAX_ASSEMS_PER_ASSEM_PLOT), start=1
iterables.chunk(assemPrototypes, MAX_ASSEMS_PER_ASSEM_PLOT), start=1
):
assemPlotImage = newReports.Image(
imageCaption,
os.path.abspath(f"{core.name}AssemblyTypes{plotNum}.png"),
)
assemPlotName = os.path.abspath(f"{core.name}AssemblyTypes{plotNum}.png")
plotting.plotAssemblyTypes(
blueprint,
assemPlotName,
assemBatch,
assemPlotName,
maxAssems=MAX_ASSEMS_PER_ASSEM_PLOT,
showBlockAxMesh=showBlockAxMesh,
hot=False,
)
currentSection.addChildElement(assemPlotImage, assemPlotName)

Expand Down
20 changes: 16 additions & 4 deletions armi/bookkeeping/report/reportingUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1060,22 +1060,34 @@ def makeCoreAndAssemblyMaps(r, cs, generateFullCoreMap=False, showBlockAxMesh=Tr
generateFullCoreMap : bool, default False
showBlockAxMesh : bool, default True
"""
assemsInCore = list(r.blueprints.assemblies.values())
assems = []
blueprints = r.blueprints
for aKey in blueprints.assemDesigns.keys():
a = blueprints.constructAssem(cs, name=aKey)
# since we will be plotting cold input heights, we need to make sure that
# that these new assemblies have access to a blueprints somewhere up the
# composite chain. normally this would happen through an assembly's parent
# reactor, but because these newly created assemblies are in the load queue,
# they will not have a parent reactor. to get around this, we just attach
# the blueprints to the assembly directly.
a.blueprints = blueprints
assems.append(a)

core = r.core
for plotNum, assemBatch in enumerate(
iterables.chunk(assemsInCore, MAX_ASSEMS_PER_ASSEM_PLOT), start=1
iterables.chunk(assems, MAX_ASSEMS_PER_ASSEM_PLOT), start=1
):
assemPlotImage = copy(report.ASSEM_TYPES)
assemPlotImage.title = assemPlotImage.title + " ({})".format(plotNum)
report.data.Report.groupsOrderFirst.insert(-1, assemPlotImage)
report.data.Report.componentWellGroups.insert(-1, assemPlotImage)
assemPlotName = os.path.abspath(f"{core.name}AssemblyTypes{plotNum}.png")
plotting.plotAssemblyTypes(
core.parent.blueprints,
assemPlotName,
assemBatch,
assemPlotName,
maxAssems=MAX_ASSEMS_PER_ASSEM_PLOT,
showBlockAxMesh=showBlockAxMesh,
hot=False,
)

# Create radial core map
Expand Down
3 changes: 1 addition & 2 deletions armi/reactor/converters/uniformMesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -980,9 +980,8 @@ def plotConvertedReactor(self):
):
assemPlotName = f"{self.convReactor.core.name}AssemblyTypes{plotNum}-rank{armi.MPI_RANK}.png"
plotting.plotAssemblyTypes(
self.convReactor.blueprints,
assemPlotName,
assemBatch,
assemPlotName,
maxAssems=6,
showBlockAxMesh=True,
)
Expand Down
49 changes: 25 additions & 24 deletions armi/utils/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -705,28 +705,25 @@ def updatePageDepthColor(self, newVal):


def plotAssemblyTypes(
blueprints=None,
fileName=None,
assems=None,
fileName=None,
maxAssems=None,
showBlockAxMesh=True,
yAxisLabel=None,
title=None,
hot=True,
) -> plt.Figure:
"""
Generate a plot showing the axial block and enrichment distributions of each assembly type in the core.

Parameters
----------
blueprints: Blueprints
The blueprints to plot assembly types of. (Either this or ``assems`` must be non-None.)
assems: list
list of assembly objects to be plotted.

fileName : str or None
Base for filename to write, or None for just returning the fig

assems: list
list of assembly objects to be plotted. (Either this or ``blueprints`` must be non-None.)

maxAssems: integer
maximum number of assemblies to plot in the assems list.

Expand All @@ -739,24 +736,14 @@ def plotAssemblyTypes(
title: str
Optionally, provide a title for the plot.

hot : bool, optional
If True, plot the hot block heights. If False, use cold heights from the inputs.

Returns
-------
fig : plt.Figure
The figure object created
"""
# input validation
if assems is None and blueprints is None:
raise ValueError(
"At least one of these inputs must be non-None: blueprints, assems"
)

# handle defaults
if assems is None:
assems = list(blueprints.assemblies.values())

if not isinstance(assems, (list, set, tuple)):
assems = [assems]

if maxAssems is not None and not isinstance(maxAssems, int):
raise TypeError("Maximum assemblies should be an integer")

Expand All @@ -765,7 +752,7 @@ def plotAssemblyTypes(
maxAssems = numAssems

if yAxisLabel is None:
yAxisLabel = "THERMALLY EXPANDED AXIAL HEIGHTS (CM)"
yAxisLabel = "Axial Heights (cm)"

if title is None:
title = "Assembly Designs"
Expand All @@ -791,6 +778,7 @@ def plotAssemblyTypes(
xAssemLoc,
xAssemEndLoc,
showBlockAxMesh,
hot,
)
xAxisLabel = re.sub(" ", "\n", assem.getType().upper())
ax.text(
Expand Down Expand Up @@ -839,6 +827,7 @@ def _plotBlocksInAssembly(
xAssemLoc,
xAssemEndLoc,
showBlockAxMesh,
hot,
):
# Set dictionary of pre-defined block types and colors for the plot
lightsage = "xkcd:light sage"
Expand All @@ -863,9 +852,19 @@ def _plotBlocksInAssembly(
xBlockLoc = xAssemLoc
xTextLoc = xBlockLoc + blockWidth / 20.0
for b in assem:
blockHeight = b.getHeight()
blockXsId = b.p.xsType
yBlockCenterLoc = yBlockLoc + blockHeight / 2.5
# get block height
if hot:
blockHeight = b.getHeight()
john-science marked this conversation as resolved.
Show resolved Hide resolved
else:
try:
blockHeight = b.getInputHeight()
except AttributeError:
raise ValueError(
f"Cannot plot cold height for block {b} in assembly {assem} "
"because it does not have access to a blueprints through any "
"of its parents. Either make sure that a blueprints is accessible "
" or plot the hot heights instead."
)

# Get the basic text label for the block
try:
Expand All @@ -880,6 +879,7 @@ def _plotBlocksInAssembly(
color = "grey"

# Get the detailed text label for the block
blockXsId = b.p.xsType
dLabel = ""
if b.hasFlags(Flags.FUEL):
dLabel = " {:0.2f}%".format(b.getFissileMassEnrich() * 100)
Expand All @@ -900,6 +900,7 @@ def _plotBlocksInAssembly(
ls="solid",
)
axis.add_patch(blockPatch)
yBlockCenterLoc = yBlockLoc + blockHeight / 2.5
axis.text(
xTextLoc,
yBlockCenterLoc,
Expand Down
17 changes: 12 additions & 5 deletions armi/utils/reportPlotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,15 +415,22 @@ def _getMechanicalVals(r):
def _getPhysicalVals(r):
avgHeight = 0.0
fuelA = r.core.getAssemblies(Flags.FUEL)
avgHeight = sum(
b.getHeight() for a in fuelA for b in a.getBlocks(Flags.FUEL)
) / len(fuelA)
radius = r.core.getCoreRadius()

# get average height
avgHeight = 0
for a in fuelA:
for b in a.getBlocks(Flags.FUEL):
try:
avgHeight += b.getInputHeight()
except AttributeError:
avgHeight += b.getHeight()
avgHeight /= len(fuelA)

radius = r.core.getCoreRadius()
labels, vals = list(
zip(
*[
john-science marked this conversation as resolved.
Show resolved Hide resolved
("Fuel height", avgHeight),
("Cold fuel height", avgHeight),
("Fuel assems", len(fuelA)),
("Assem weight", r.core.getFirstAssembly(Flags.FUEL).getMass()),
("Core radius", radius),
Expand Down
30 changes: 25 additions & 5 deletions armi/utils/tests/test_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import os
import unittest

import matplotlib.pyplot as plt
import numpy as np

from armi import settings
Expand Down Expand Up @@ -58,15 +59,17 @@ def test_plotDepthMap(self): # indirectly tests plot face map
def test_plotAssemblyTypes(self):
with TemporaryDirectoryChanger():
plotPath = "coreAssemblyTypes1.png"
plotting.plotAssemblyTypes(self.r.core.parent.blueprints, plotPath)
plotting.plotAssemblyTypes(
list(self.r.core.parent.blueprints.assemblies.values()), plotPath
)
self._checkFileExists(plotPath)

if os.path.exists(plotPath):
os.remove(plotPath)

plotPath = "coreAssemblyTypes2.png"
plotting.plotAssemblyTypes(
self.r.core.parent.blueprints,
list(self.r.core.parent.blueprints.assemblies.values()),
plotPath,
yAxisLabel="y axis",
title="title",
Expand All @@ -76,12 +79,29 @@ def test_plotAssemblyTypes(self):
if os.path.exists(plotPath):
os.remove(plotPath)

with self.assertRaises(ValueError):
plotting.plotAssemblyTypes(None, plotPath, None)

if os.path.exists(plotPath):
os.remove(plotPath)

def test_plotBlocksInAssembly(self):
_fig, ax = plt.subplots(figsize=(15, 15), dpi=300)
xBlockLoc, yBlockHeights, yBlockAxMesh = plotting._plotBlocksInAssembly(
ax,
self.r.core.getFirstAssembly(Flags.FUEL),
True,
[],
set(),
0.5,
5.6,
True,
hot=True,
)
self.assertEqual(xBlockLoc, 0.5)
self.assertEqual(yBlockHeights[0], 25.0)
yBlockAxMesh = list(yBlockAxMesh)[0]
self.assertIn(10.0, yBlockAxMesh)
self.assertIn(25.0, yBlockAxMesh)
self.assertIn(1, yBlockAxMesh)

def test_plotBlockFlux(self):
with TemporaryDirectoryChanger():
xslib = isotxs.readBinary(ISOAA_PATH)
Expand Down
33 changes: 33 additions & 0 deletions armi/utils/tests/test_reportPlotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@

import numpy as np

from armi.reactor.flags import Flags
from armi.reactor.tests import test_reactors
from armi.tests import TEST_ROOT
from armi.utils.directoryChangers import TemporaryDirectoryChanger
from armi.utils.reportPlotting import (
_getPhysicalVals,
createPlotMetaData,
keffVsTime,
movesVsCycle,
Expand All @@ -47,6 +49,37 @@ def test_radar(self):
"""Test execution of radar plot. Note this has no asserts and is therefore a smoke test."""
r2 = copy.deepcopy(self.r)
plotCoreOverviewRadar([self.r, r2], ["Label1", "Label2"])
self.assertTrue(os.path.exists("reactor_comparison.png"))

def test_getPhysicalVals(self):
dims, labels, vals = _getPhysicalVals(self.r)
self.assertEqual(dims, "Dimensions")

self.assertEqual(labels[0], "Cold fuel height")
self.assertEqual(labels[1], "Fuel assems")
self.assertEqual(labels[2], "Assem weight")
self.assertEqual(labels[3], "Core radius")
self.assertEqual(labels[4], "Core aspect ratio")
self.assertEqual(labels[5], "Fissile mass")
self.assertEqual(len(labels), 6)

self.assertEqual(vals[0], 25.0)
self.assertEqual(vals[1], 1)
self.assertAlmostEqual(vals[2], 52474.8927038, delta=1e-5)
self.assertEqual(vals[3], 16.8)
self.assertAlmostEqual(vals[5], 4290.60340961, delta=1e-5)
self.assertEqual(len(vals), 6)

# this test will use getInputHeight() instead of getHeight()
radius = self.r.core.getCoreRadius()
avgHeight = 0
fuelA = self.r.core.getAssemblies(Flags.FUEL)
for a in fuelA:
for b in a.getBlocks(Flags.FUEL):
avgHeight += b.getInputHeight()
avgHeight /= len(fuelA)
coreAspectRatio = (2 * radius) / avgHeight
self.assertEqual(vals[4], coreAspectRatio)

def test_createPlotMetaData(self):
title = "test_createPlotMetaData"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ def buildSystems():
# build ARMI objects
o = case.initializeOperator()
fig = plotting.plotAssemblyTypes(
case.bp,
list(case.bp.assemblies.values()),
None,
showBlockAxMesh=True,
)
Expand Down
1 change: 1 addition & 0 deletions doc/release/0.5.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ API Changes

Bug Fixes
---------
#. Fix assembly plots to use initial block heights. (`PR#1998 <https://github.com/terrapower/armi/pull/1998>`_)
#. TBD

Quality Work
Expand Down