Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 30

Python S_N Solver: Source Iteration for Slab Geometry

Recommended resources

Introduction

In our previous lesson, we outlined the source iteration algorithm, a powerful iterative method for solving the coupled discrete ordinates (S) equations. We established that by making an initial guess for the scattering source, we can perform a "transport sweep" across the spatial domain to find the angular flux, which in turn gives us a better estimate for the source. This lesson transitions from that theoretical framework to practical application. Your goal is to implement the source iteration algorithm in Python to solve the S equations for a slab problem.

This is a milestone in our course. You will build a functional transport solver from the ground up, translating the mathematical and algorithmic concepts we've discussed into a working program. This process will solidify your understanding of how the discretized equations, boundary conditions, and iterative scheme all fit together.


The Anatomy of an S Solver

Before diving into the code, let's lay out the essential components of our Python solver. A typical implementation consists of four main parts:

  1. Setup and Initialization: This involves defining all the problem's physical and numerical parameters.

    • Physical Parameters: Slab width, total cross section , scattering cross section , and the external source distribution . For simplicity, we'll start with isotropic scattering.
    • Numerical Parameters: The order of the S approximation (), the number of spatial cells (), and the convergence tolerance ().
    • Data Structures: We will use NumPy arrays to store the angular flux , scalar flux , and the source terms. For instance, the angular flux at cell edges will be a 2D array of size (N, J+1).
    • Quadrature Set: We need the discrete angles and their corresponding weights , which can be generated using a Gauss-Legendre quadrature routine. The numpy.polynomial.legendre.leggauss function is perfectly suited for this.
  2. The Main Iteration Loop: This is the high-level control structure, typically a while loop, that continues until the scalar flux converges.

  3. The Transport Sweep: The computational core of the solver. For each iteration, this part loops through all discrete angles and "sweeps" across the spatial grid to update the angular flux based on the source from the previous iteration.

  4. Update and Convergence Check: After a full transport sweep (over all angles), the scalar flux is re-calculated from the new angular flux. This new scalar flux is then compared to the one from the previous iteration to check if the solution has converged.

This entire process directly corresponds to the "Inner Iteration" loop in the flowchart we examined in the last lesson.

This flowchart shows the iterative solution process. Our focus today is on implementing the blue "Inner Iteration" loop: computing the total source from a guessed flux, solving for a new flux (the transport sweep), and checking for convergence.

A Look at a Complete Implementation

It's often helpful to see a finished product before you start building. The appendix of the thesis we consulted previously contains a full Python implementation of an S solver. While it solves a more complex "spectral" version of the transport equation, its fundamental structure is identical to what we need.

Your task is not to replicate this code verbatim, but to use it as a reference. As you read it, mentally simplify the problem: our standard S solver corresponds to their case where the number of spectral moments M is 0. This means you can ignore the loops over m and any terms involving m>0.

SPECTRAL DISCRETE ORDINATES METHOD WITH LAGUERRE POLYNOMIAL TRUNCATION OF ORDER N (SPECTRAL-LTSN) SOLUTIONS TO THE GENERALIZED LINEAR BOLTZMANN EQUATION

This appendix provides a complete Python code for an advanced S_N solver. We will use it as a guide for the structure and implementation of our own, simpler solver.

In the "Appendix: Python Code...", focus on understanding the overall flow. Start by looking at the main iteration loop, which begins here. Step 1: See how the scattering source S is computed from the previous iteration's flux psi. Note that since this is a spectral code, it has a source S for each moment m. In our case, we only have one moment (m=0), so S is just a 1D array over space. Step 2: Examine the "Transport sweep" section. Notice the loop for n in range(N): over the angles. Inside, it branches based on the sign of mu[n]. This is the implementation of the forward and backward sweeps we discussed. The core calculation uses coefficients a and b, which are the pre-calculated terms from the diamond-difference formula. Step 3: Finally, look at the convergence check, which computes the maximum absolute difference between psi and psi_old. Again, don't worry about the details of m > 0 or the "spectral" reconstruction. Focus on the core logic for the m=0 case, which is our standard angular flux.


Building the Solver: A Step-by-Step Guide

Now, let's construct our solver piece by piece. We'll use the diamond-difference scheme we derived previously.

Step 1: Initialization

First, set up your Python script by importing numpy and defining all necessary parameters. You will need to initialize arrays for the scalar flux (at cell centers) and the angular flux (at cell edges).

import numpy as np
import numpy.polynomial.legendre as leg




# Physical Parameters
width = 20.0  # cm
Sigma_t = 1.0 # Total cross section
Sigma_s = 0.9 # Scattering cross section (c = 0.9)




# Numerical Parameters
N = 16        # S_N order (must be even)
J = 200       # Number of spatial cells
tolerance = 1e-6




# Discretization
x_edges = np.linspace(0, width, J + 1)
x_centers = 0.5 * (x_edges[:-1] + x_edges[1:])
dx = width / J
mu, w = leg.leggauss(N) # Gauss-Legendre quadrature




# Source (e.g., uniform in the center)
Q = np.zeros(J)
Q[int(J/2)-5 : int(J/2)+5] = 1.0




# Initialize fluxes and source
psi = np.zeros((N, J + 1)) # Angular flux at cell edges
phi = np.zeros(J)          # Scalar flux at cell centers
scattering_source = np.zeros(J)

Step 2: The Main Iteration Loop

Set up the while loop that drives the iteration. Inside, you'll first store the current scalar flux to compare against later, then calculate the total source for this iteration.




# Iteration
for k in range(1000): # Max iterations
    phi_old = phi.copy()




    # Calculate total source (isotropic scattering)
    total_source = 0.5 * Sigma_s * phi_old + Q
    



    # ... Transport Sweep will go here ...
    



    # ... Update Scalar Flux will go here ...
    



    # ... Convergence Check will go here ...

Step 3: The Transport Sweep

This is the most involved part. You will loop through each discrete angle . Depending on the sign of , you sweep across the grid, updating the angular flux at each cell edge.

The diamond-difference update equation for the outgoing flux from a cell, say , in terms of the incoming flux and the cell-centered source , is:

Note the use of to make the equation general for both sweep directions.




# (Inside the main loop)
# --- Transport Sweep ---
for m in range(N):
    if mu[m] > 0: # Forward sweep (left to right)



        # Boundary condition (vacuum at x=0)
        psi[m, 0] = 0.0 
        for i in range(J): # Loop over cells



            # Diamond difference formula
            psi[m, i+1] = ((1 - Sigma_t * dx / (2 * mu[m])) / (1 + Sigma_t * dx / (2 * mu[m]))) * psi[m, i] \
                        + ((total_source[i] * dx / mu[m]) / (1 + Sigma_t * dx / (2 * mu[m])))
    else: # Backward sweep (right to left)



        # Boundary condition (vacuum at x=width)
        psi[m, J] = 0.0
        for i in range(J - 1, -1, -1): # Loop over cells, right to left



            # Diamond difference formula (note mu[m] is negative)
            psi[m, i] = ((1 + Sigma_t * dx / (2 * mu[m])) / (1 - Sigma_t * dx / (2 * mu[m]))) * psi[m, i+1] \
                      - ((total_source[i] * dx / mu[m]) / (1 - Sigma_t * dx / (2 * mu[m])))

A small derivation note on the backward sweep formula: it's just the forward-sweep formula algebraically solved for instead of .

Step 4: Update Scalar Flux and Check Convergence

After the sweeps for all angles are complete, you have the new angular fluxes at all cell edges. Use these to calculate the new scalar flux at the cell centers and then check for convergence.

The cell-center angular flux is the average of its edge fluxes: . The scalar flux is the weighted sum of these cell-center angular fluxes.




# (Inside the main loop, after the sweep)
# --- Update Scalar Flux ---
# First, get cell-centered angular flux from edge fluxes
psi_centers = 0.5 * (psi[:, :-1] + psi[:, 1:])



# Now, compute scalar flux by summing over angles
phi = np.sum(w[:, np.newaxis] * psi_centers, axis=0)




# --- Convergence Check ---
relative_error = np.max(np.abs(phi - phi_old) / (phi + 1e-10)) # Add small number to avoid division by zero
print(f"Iteration {k}: Relative Error = {relative_error:.6e}")
if relative_error < tolerance:
    print("Convergence reached.")
    break

A Pedagogical Perspective

Another excellent resource, "A practical guide to writing a radiative transfer code," develops a very similar solver using the Gauss-Seidel (GS) method, which is conceptually identical to our source iteration. The paper is written as a tutorial, building the code piece-by-piece with clear explanations. While its focus is atmospheric science, the numerical techniques are universal. Reading through its implementation can provide valuable insights into structuring your code.

[PDF] A practical guide to writing a radiative transfer code

This guide provides a step-by-step tutorial for creating an iterative radiative transfer solver, reinforcing the concepts we're implementing.

Skim through Section 3.6, "Numerical simulation of multiple scattering using Gauss-Seidel iteration." Pay attention to the overall structure. The function gauss_seidel_iterations_m() is the heart of the solver. Notice the initial setup of parameters and grids. The code then computes the initial guess for the flux, which is analogous to our first iteration with phi=0. The main part is the iteration loop. Inside, it calculates the source J and then performs downward (forward) and upward (backward) sweeps to update the intensity Idn and Iup. This is precisely the logic of our transport sweep. The main program, described in Section 3.6.3 and shown in the script gsit.py, shows how these iterative calls are put together. The key takeaway is seeing the same pattern—initialize, loop, calculate source, sweep, update—in a different context, which confirms its fundamental importance.


Conclusion

You now have a complete blueprint for building a 1D S transport code. By combining the theoretical steps from the previous lesson with the practical implementation details and reference codes from this one, you are equipped to write your first deterministic solver.

Key Takeaways:

  • An S solver is built around a main iteration loop that continues until the scalar flux converges.
  • Each iteration involves two key steps:
    1. Calculating the total source using the scalar flux from the previous iteration.
    2. Performing a transport sweep for all angles to find the new angular flux based on this fixed source.
  • The transport sweep consists of forward sweeps () from left-to-right and backward sweeps () from right-to-left.
  • The diamond-difference scheme provides an algebraic formula to calculate the outgoing flux from a cell given the incoming flux and the cell's source.
  • After the sweep, the scalar flux is updated, and the relative change is used to check for convergence.

Preview of the Next Lesson:

After you have implemented and tested your solver, you may notice that for problems with high scattering () and optically thick domains, the convergence of source iteration can become extremely slow. In the next lesson, we will investigate why this happens and introduce a powerful technique called Diffusion Synthetic Acceleration (DSA) to dramatically speed up the convergence.