5.4.5. CMFD Convergence and Diagnostics

This tutorial covers when a CMFD solve stops and how to read the CMFD diagnostics:

  • the two convergence tests of PowerIterationKEigenSolver, k_tol and fission_source_tol,

  • verbose=True diagnostics and the solver accessors,

  • coarse values that keep the transport flux, and skipped corrections forced with petsc_options,

  • CMFD for the adjoint problem.

5.4.5.1. The C5G7 model

The C5G7 benchmark [Lewis et al., NEA/NSC/DOC(2003)16] is a quarter core of four 17 x 17 pin assemblies and a water reflector. The UO\(_2\) assemblies sit on the diagonal. The MOX assemblies have three enrichment zones (4.3%, 7.0% and 8.7%). Every assembly has 24 guide tubes and a central fission chamber. The pin pitch is 1.26 cm and the reflector is one assembly (21.42 cm) thick. The core center is in the lower-left corner, so the left and bottom boundaries are reflecting and the right and top boundaries are vacuum. The benchmark provides seven-group cross sections with upscattering in the four thermal groups.

The tutorials in this series use two models of that core.

  • The pin-homogenized model mixes each fuel pin with its moderator by volume, so every pin cell is one 1.26 cm square mesh cell. It keeps the assembly layout, the MOX zoning, the guide tubes and the reflector, which are what make C5G7 hard for unaccelerated power iteration, and it solves in a few seconds. The option studies use it.

  • The heterogeneous model in the benchmark tutorial represents each pin by a square of the same area as the round pin, surrounded by moderator.

Both use a 2 x 2 KBA partition, so run the generated scripts with four MPI processes. A light quadrature keeps the run times short. Production calculations need more directions.

5.4.5.2. Model and measurement code

The next two cells build the C5G7 problem and measure a solve. They are the same in every tutorial of this series. solve() builds a fresh problem for each case, so every solve starts from the same state. Its cmfd argument holds the CMFDAcceleration options, and without it the power iteration is unaccelerated. Its solver argument holds further PowerIterationKEigenSolver options, such as sweeps_per_update. It returns the eigenvalue, the number of power iterations (outers), the number of transport sweeps, the number of CMFD coarse cells, the number of skipped CMFD corrections, whether the solve converged, the wall time, and the fission rate of every fuel pin normalized to the average fuel pin. The wall time covers building the problem, initializing the solver, and the solve. Building the problem is the same in every case.

[ ]:
import math
from pathlib import Path

from mpi4py import MPI
from pyopensn.aquad import GLCProductQuadrature2DXY
from pyopensn.context import Finalize
from pyopensn.fieldfunc import FieldFunctionGridBased
from pyopensn.math import Vector3
from pyopensn.mesh import KBAGraphPartitioner, OrthogonalMeshGenerator
from pyopensn.solver import (
    CMFDAcceleration,
    DiscreteOrdinatesProblem,
    PowerIterationKEigenSolver,
)
from pyopensn.xs import MultiGroupXS

comm = MPI.COMM_WORLD
rank = comm.rank
tutorial_dir = Path(__file__).resolve().parent if "__file__" in globals() else Path.cwd()
xs_dir = next(
    path / "test/assets/xs/c5g7"
    for path in (tutorial_dir, *tutorial_dir.parents)
    if (path / "test/assets/xs/c5g7").is_dir()
)
[ ]:
PITCH = 1.26  # pin pitch (cm)
PIN_RADIUS = 0.54  # fuel pin radius (cm)
ASSEMBLY_PINS = 17
CORE_PINS = 2 * ASSEMBLY_PINS  # fuel-assembly pins per side of the quarter core
DOMAIN_PINS = 3 * ASSEMBLY_PINS  # including the water reflector

WATER, UO2, MOX_43, MOX_70, MOX_87, GUIDE_TUBE, FISSION_CHAMBER = range(7)
XS_FILES = [
    "XS_water",
    "XS_UO2",
    "XS_4_3pMOX",
    "XS_7pMOX",
    "XS_8_7pMOX",
    "XS_guide_tube",
    "XS_fission_chamber",
]
FUEL = (UO2, MOX_43, MOX_70, MOX_87)
GUIDE_TUBES = {
    (2, 5), (2, 8), (2, 11), (3, 3), (3, 13), (5, 2), (5, 5), (5, 8), (5, 11), (5, 14),
    (8, 2), (8, 5), (8, 11), (8, 14), (11, 2), (11, 5), (11, 8), (11, 11), (11, 14),
    (13, 3), (13, 13), (14, 5), (14, 8), (14, 11),
}
# One quarter of the MOX assembly, mirrored about its center row and column.
# 1, 2 and 3 are 4.3%, 7.0% and 8.7% MOX, G is a guide tube and F the fission chamber.
MOX_QUARTER = [
    "111111111",
    "122222222",
    "12222G22G",
    "122G23333",
    "122233333",
    "12G33G33G",
    "122333333",
    "122333333",
    "12G33G33F",
]
MOX_ZONES = {"1": MOX_43, "2": MOX_70, "3": MOX_87}


def pin_material(px, py):
    """Return the material of the pin cell in column px and row py of the domain."""
    if px >= CORE_PINS or py >= CORE_PINS:
        return WATER
    i, j = py % ASSEMBLY_PINS, px % ASSEMBLY_PINS
    if (i, j) == (8, 8):
        return FISSION_CHAMBER
    if (i, j) in GUIDE_TUBES:
        return GUIDE_TUBE
    if px // ASSEMBLY_PINS == py // ASSEMBLY_PINS:
        return UO2
    return MOX_ZONES[MOX_QUARTER[min(i, 16 - i)][min(j, 16 - j)]]


def load_cross_sections(homogenized):
    """Load the seven C5G7 materials, mixed with water over the pin cell if homogenized."""
    cross_sections = []
    for name in XS_FILES:
        xs = MultiGroupXS()
        xs.LoadFromOpenSn(str(xs_dir / f"{name}.xs"))
        cross_sections.append(xs)
    if not homogenized:
        return cross_sections
    fuel_fraction = math.pi * PIN_RADIUS**2 / PITCH**2
    water = cross_sections[WATER]
    return [water] + [
        MultiGroupXS.Combine([(xs, fuel_fraction), (water, 1.0 - fuel_fraction)])
        for xs in cross_sections[1:]
    ]


def make_mesh(homogenized):
    """Build the quarter core on a 2 x 2 KBA partition, so run with four MPI processes."""
    if homogenized:
        nodes = [PITCH * p for p in range(DOMAIN_PINS + 1)]
    else:
        side = math.sqrt(math.pi) * PIN_RADIUS  # square pin with the area of the round one
        gap = 0.5 * (PITCH - side)
        nodes = [PITCH * p + offset for p in range(CORE_PINS) for offset in (0.0, gap, gap + side)]
        nodes += [PITCH * (CORE_PINS + 0.5 * k) for k in range(2 * ASSEMBLY_PINS + 1)]
    cut = PITCH * ASSEMBLY_PINS
    mesh = OrthogonalMeshGenerator(
        node_sets=[nodes, nodes],
        partitioner=KBAGraphPartitioner(nx=2, ny=2, xcuts=[cut], ycuts=[cut]),
    ).Execute()
    mesh.SetOrthogonalBoundaries()

    def block_id(centroid, old_block_id):
        px, py = int(centroid.x // PITCH), int(centroid.y // PITCH)
        if not homogenized:
            local_x, local_y = centroid.x - px * PITCH, centroid.y - py * PITCH
            if not (gap < local_x < gap + side and gap < local_y < gap + side):
                return WATER
        return pin_material(px, py)

    mesh.SetBlockIDFromFunction(block_id)
    return mesh


def make_problem(
    homogenized=True,
    n_azimuthal=4,
    group_ranges=((0, 6),),
    inner_linear_method="classic_richardson",
    l_max_its=4,
    adjoint=False,
    verbose=False,
):
    """Build the C5G7 quarter-core transport problem."""
    cross_sections = load_cross_sections(homogenized)
    quadrature = GLCProductQuadrature2DXY(
        n_polar=2, n_azimuthal=n_azimuthal, scattering_order=0
    )
    problem = DiscreteOrdinatesProblem(
        mesh=make_mesh(homogenized),
        num_groups=7,
        groupsets=[
            {
                "groups_from_to": group_range,
                "angular_quadrature": quadrature,
                "inner_linear_method": inner_linear_method,
                "l_max_its": l_max_its,
                "l_abs_tol": 1.0e-10,
            }
            for group_range in group_ranges
        ],
        xs_map=[{"block_ids": [m], "xs": xs} for m, xs in enumerate(cross_sections)],
        boundary_conditions=[
            {"name": "xmin", "type": "reflecting"},
            {"name": "ymin", "type": "reflecting"},
        ],
        options={
            "adjoint": adjoint,
            "use_precursors": False,
            "power_default_kappa": 1.0,
            "verbose_inner_iterations": False,
            "verbose_outer_iterations": verbose,
        },
    )
    return problem, cross_sections
[ ]:
def pin_fission_rates(problem, cross_sections):
    """Return the fission rate of every fuel pin, normalized to the average fuel pin.

    Each pin center is the center of a rectangular cell, where the bilinear PWLD flux equals
    its cell average.
    """
    pins = [
        (px, py)
        for py in range(CORE_PINS)
        for px in range(CORE_PINS)
        if pin_material(px, py) in FUEL
    ]
    points = [Vector3((px + 0.5) * PITCH, (py + 0.5) * PITCH, 0.0) for px, py in pins]
    flux = FieldFunctionGridBased.GetPointValues(problem.GetScalarFluxFieldFunction(), points)
    rates = []
    for n, (px, py) in enumerate(pins):
        sigma_f = cross_sections[pin_material(px, py)].sigma_f
        rates.append(sum(sigma_f[g] * flux[g][n][0] for g in range(len(sigma_f))))
    mean = sum(rates) / len(rates)
    return {pin: rate / mean for pin, rate in zip(pins, rates)}


def solve(label, cmfd=None, solver=None, k_tol=1.0e-7, max_iters=400, **problem_options):
    """Build a fresh problem, solve it with power iteration, and return the metrics.

    cmfd holds the CMFDAcceleration options. Without it the power iteration is unaccelerated.
    solver holds further PowerIterationKEigenSolver options, such as sweeps_per_update.
    """
    comm.Barrier()
    start = MPI.Wtime()
    problem, cross_sections = make_problem(**problem_options)
    acceleration = None
    solver_options = {"problem": problem, "k_tol": k_tol, "max_iters": max_iters}
    solver_options.update(solver or {})
    if cmfd is not None:
        acceleration = CMFDAcceleration(problem=problem, **cmfd)
        solver_options["acceleration"] = acceleration
    power_iteration = PowerIterationKEigenSolver(**solver_options)
    power_iteration.Initialize()
    power_iteration.Execute()
    seconds = comm.allreduce(MPI.Wtime() - start, op=MPI.MAX)
    return {
        "label": label,
        "k": power_iteration.GetEigenvalue(),
        "outers": power_iteration.GetNumPowerIterations(),
        "sweeps": power_iteration.GetNumSweeps(),
        "converged": power_iteration.IsConverged(),
        "coarse_cells": acceleration.GetNumCoarseCells() if acceleration else 0,
        "skipped": acceleration.GetNumSkippedCorrections() if acceleration else 0,
        "seconds": seconds,
        "pins": pin_fission_rates(problem, cross_sections),
    }


def report(results, k_reference, pin_reference=None):
    """Print one row per solve and one stable key per metric for the regression tests."""
    if rank != 0:
        return
    header = f"{'case':<34}{'k_eff':>12}{'k error':>10}{'outers':>8}{'sweeps':>8}"
    header += f"{'coarse':>8}{'skips':>6}{'conv':>5}"
    header += f"{'pin error':>10}" if pin_reference else ""
    print(header + f"{'time (s)':>10}")
    for r in results:
        k_error = r["k"] - k_reference
        row = f"{r['label']:<34}{r['k']:>12.8f}{k_error:>10.1e}{r['outers']:>8}{r['sweeps']:>8}"
        row += f"{r['coarse_cells']:>8}{r['skipped']:>6}{int(r['converged']):>5}"
        if pin_reference:
            row += f"{max_pin_error(r, pin_reference):>10.1e}"
        print(row + f"{r['seconds']:>10.2f}")
    for r in results:
        key = r["label"].replace(" ", "_")
        print(f"{key} k-effective error={r['k'] - k_reference:.6e}")
        print(f"{key} converged={int(r['converged'])}")


def max_pin_error(result, pin_reference):
    """Largest difference of the normalized pin fission rates from the reference."""
    return max(abs(result["pins"][pin] - value) for pin, value in pin_reference.items())

5.4.5.3. A tightly converged reference

The reference is a CMFD solve with the series settings of the basics tutorial and tolerances far tighter than the ones used in the cases below. Its eigenvalue and pin fission rates measure the error of each case. Its eigenvalue agrees with the reference eigenvalue of the series, 1.188819461, which unaccelerated power iteration converged to k_tol=1e-11 and fission_source_tol=1e-9 also gives.

[ ]:
PIN_LATTICE = {
    "type": "reactor_lattice",
    "origin": [0.0, 0.0],
    "pitch": [PITCH, PITCH],
    "shape": [DOMAIN_PINS, DOMAIN_PINS],
}
SERIES = {"coarse_mesh": PIN_LATTICE, "coarse_groups": 2}

reference = solve(
    "reference", cmfd=SERIES, solver={"fission_source_tol": 1.0e-10}, k_tol=1.0e-11
)
K_REFERENCE = reference["k"]
PIN_REFERENCE = reference["pins"]
assert reference["converged"]
assert abs(K_REFERENCE - 1.188819461) < 1.0e-9

5.4.5.4. When the solve stops

Power iteration reports convergence only when the enabled tests pass and the accelerator, if any, allows it. There are two tests:

  • the eigenvalue test: the relative change of k between power iterations is below k_tol * (1 - rho) in two consecutive iterations,

  • the fission-source test: the root-mean-square relative change of the cell fission sources, each normalized by the total fission production, is below fission_source_tol * (1 - rho). The default is 1e-6, and 0 disables the test.

rho is the convergence rate estimated from successive changes, so the tolerances bound the estimated errors rather than the changes. With CMFD, an update whose correction was skipped never ends the iteration. The solve also stops after max_iters power iterations, and if the tests have not passed by then, IsConverged() is false, as with the failing coarse solver below.

The eigenvalue converges much faster than the flux shape, so stopping on the eigenvalue alone can leave the flux, and the pin powers, less converged than the eigenvalue suggests. The three solves below use k_tol=1e-7 and turn the fission-source test off, leave it at its default, and tighten it.

[ ]:
stop_results = [
    solve("k only", cmfd=SERIES, solver={"fission_source_tol": 0.0}),
    solve("default fission source test", cmfd=SERIES),
    solve("fission source 1e-8", cmfd=SERIES, solver={"fission_source_tol": 1.0e-8}),
]
report(stop_results, K_REFERENCE, PIN_REFERENCE)

With only the eigenvalue test, the solve stops after 34 power iterations. Its eigenvalue error is about 1.6e-7, but its pin fission rates are off by 4.1e-6, 25 times more. The default fission-source test needs 39 power iterations and gives pin fission rates within 1.1e-6, and fission_source_tol=1e-8 needs 53 and gives 2.7e-8. The status lines of the basics tutorial show the same: in the last ten power iterations the fission-source change is five to thirty times the change of k. Keep the fission-source test on for any result that uses the flux, and set fission_source_tol to the accuracy the pin powers need.

5.4.5.5. Diagnostics

At setup, CMFD logs the coarse mesh, the coarse energy groups, the number of coarse unknowns and the coarse linear solver, for example

CMFD coarse linear solver: LU (SuperLU_DIST) (estimated LU memory 0.0105529 GiB, budget 1 GiB per rank, 4 GiB in total).

CMFD factorizes the coarse operator with SuperLU_DIST or MUMPS when the estimated memory of its LU factorization is at most 1 GiB per MPI rank, and otherwise uses FGMRES with an additive Schwarz preconditioner and ILU(0) subdomain solves.

verbose=True on CMFDAcceleration adds stable CMFD_ACCEL lines and a few summary lines for the first five power iterations and every 25th one. The next solve stops after two power iterations to keep the output short, and it also turns on the status lines of the problem.

[ ]:
verbose_result = solve("verbose", cmfd={**SERIES, "verbose": True}, max_iters=2, verbose=True)

The output contains

  • CMFD_ACCEL category=coarse_mesh lines with the coarse-mesh statistics,

  • the optical thickness of the coarse cells along each axis, which is at most 1.3 mean free paths here (the user guide explains why it matters):

    CMFD coarse-cell optical thickness: max x = 1.2797, y = 1.2797, z = 0 mean free paths.
    
  • the signs of the coarse operator and the negative coarse fluxes of each coarse group:

    CMFD operator signs: nonpositive_diagonals = 0, positive_off_diagonals = 0, negative_coarse_fluxes = 0, rows = 5202
    CMFD negative coarse fluxes by coarse group (count and most negative relative to the group maximum): 0:0(0) 1:0(0)
    

    Nonpositive diagonals, positive off-diagonals and negative coarse fluxes make the coarse operator lose the M-matrix property, which makes coarse solves unreliable. Signed transport iterates can cause them. Here there are none.

  • the residuals of the coarse balance with the transport currents, which decrease as the transport iterate converges,

  • CMFD_ACCEL category=correction lines with the transport, coarse and applied eigenvalues, whether the correction was skipped, and the number of coarse values that kept the transport flux (kept_coarse_values),

  • CMFD_ACCEL category=timing lines with the time of each CMFD phase (restriction, homogenization, assembly, coarse solve, prolongation and transport), the number of coarse power iterations and whether the coarse linear solves converged.

After a solve, these accessors summarize it:

  • PowerIterationKEigenSolver.IsConverged(): whether both convergence tests passed,

  • GetNumPowerIterations() and GetNumSweeps(): the work done,

  • GetFissionSourceChange(): the fission-source change of the last power iteration,

  • CMFDAcceleration.GetNumCoarseCells(): the size of the coarse mesh,

  • GetNumAppliedCorrections() and GetNumSkippedCorrections(): how many corrections were applied and skipped.

5.4.5.6. Kept coarse values and skipped corrections

CMFD scales the transport flux of each coarse cell and coarse group by the ratio of the corrected to the uncorrected coarse flux. Where that ratio would be negative or non-finite, or where the restricted transport flux is itself negative, the correction would flip or amplify the flux. Those coarse values keep the transport flux, scaled to the amplitude of the coarse solution, and the rest of the correction is applied. All ratios tend to one at convergence, so the converged solution does not depend on this.

With a three-iteration GMRES transport update, the first transport updates are rough. CMFD warns once:

CMFD kept the transport flux in 47 of 5202 coarse values at update 0 because the correction would
change its sign. This happens where the transport flux is negative, for example in elongated
cells. verbose=True lists where. This warning is not repeated.

With verbose=True, the kept_coarse_values metric is 47 in the first correction, 11 in the second and 0 in the third to fifth, the last that verbose reports before the 25th. The metric counts every kept value on all ranks. CMFD also lists a sample of their locations, at most three per rank in each correction, for example

CMFD keeps the transport flux at coarse cell 2242 (62.37, 54.81, 0), coarse group 0: transport 0.0466354, coarse -4.41892e-05

Here the kept values lie in the reflector next to the vacuum boundaries, where the transport flux is positive but the coarse solution of these early iterates is slightly negative.

CMFD skips a whole correction only when it cannot trust it: when a coarse linear solve fails or leaves a large true residual (coarse_linear_solve_not_converged), when the coarse eigensolve breaks down with a coarse production or k that is not positive and finite, or does not meet its tolerances within 1000 iterations (coarse_eigensolve_failed), or when the corrected flux gives an invalid k or a non-finite flux (invalid_k, nonfinite_flux). That power iteration then keeps its unaccelerated transport update and its raw k. A failed coarse linear solve can be forced with petsc_options, which passes PETSc options to the coarse linear solver after its automatic choice. The options prefix is the accelerator name ("CMFDAcceleration" by default) with nothing in between. A GMRES coarse solve limited to zero iterations never converges, so every correction is skipped. The solve is limited to 10 power iterations.

[ ]:
FAILING_COARSE_SOLVER = (
    "-CMFDAccelerationksp_type gmres -CMFDAccelerationksp_max_it 0 "
    "-CMFDAccelerationpc_type jacobi"
)
skip_results = [
    solve(
        "GMRES 3 update",
        cmfd=SERIES,
        solver={"sweeps_per_update": 3},
        inner_linear_method="petsc_gmres",
    ),
    solve(
        "failing coarse solver",
        cmfd={**SERIES, "petsc_options": FAILING_COARSE_SOLVER},
        max_iters=10,
    ),
]
report(skip_results, K_REFERENCE, PIN_REFERENCE)

The GMRES update skips no correction and converges in 18 power iterations. With the failing coarse solver, every correction is skipped. Each skip logs

CMFD correction skipped because a coarse linear solve did not converge.

and after five consecutive skips CMFD warns:

CMFD skipped the last 5 corrections (last reason: coarse_linear_solve_not_converged). Power
iteration is proceeding without CMFD acceleration. Configure a stronger coarse linear solver with
petsc_options, or reduce the coarse system with a coarser coarse_mesh or fewer coarse_groups.

Kept coarse values in the first few corrections are harmless. An occasional skip is also harmless, but persistent skips mean that CMFD is not accelerating the solve. For coarse_linear_solve_not_converged, configure a stronger coarse solver with petsc_options, or reduce the coarse system with larger coarse cells or fewer coarse groups.

5.4.5.7. Adjoint problems

CMFD also accelerates the adjoint k-eigenvalue problem. It homogenizes the transposed scattering and production, and the adjoint eigenvalue equals the forward one. With the series settings the adjoint solve converges in 51 power iterations, against 39 for the forward problem.

[ ]:
adjoint = solve("adjoint", cmfd=SERIES, adjoint=True)
report([adjoint], K_REFERENCE)
[ ]:
results = [reference] + stop_results + [skip_results[0], adjoint]
for result in results:
    assert result["converged"], result["label"]
    assert abs(result["k"] - K_REFERENCE) < 1.0e-6, result["label"]
k_only, default_test, tight_test = stop_results
assert max_pin_error(k_only, PIN_REFERENCE) > 2 * max_pin_error(default_test, PIN_REFERENCE)
assert max_pin_error(tight_test, PIN_REFERENCE) < max_pin_error(default_test, PIN_REFERENCE) / 10
assert skip_results[0]["skipped"] == 0
failing = skip_results[1]
assert not failing["converged"]
assert failing["skipped"] == failing["outers"] == 10
if rank == 0:
    for result in stop_results:
        key = result["label"].replace(" ", "_")
        print(f"{key} max pin error={max_pin_error(result, PIN_REFERENCE):.3e}")

5.4.5.8. Finalize (for Jupyter Notebook only)

In script mode, PyOpenSn handles finalization automatically. In a Jupyter kernel, finalize OpenSn before MPI.

[ ]:
if "opensn_console" not in globals():
    from IPython import get_ipython

    if get_ipython() is not None:
        Finalize()
        MPI.Finalize()