Module 11: C++ Architecture for a Finite-Volume CFD Framework
Design a reusable finite-volume framework in C++ by connecting mesh geometry, scalar fields, boundary conditions, face-based fluxes, equation assembly, linear solvers, and automated numerical tests.
1. Introduction: From a Solver to a Framework
In Module 10, we built a simple one-dimensional heat-conduction solver. It stored temperatures in a vector, assembled a tridiagonal matrix, solved the resulting algebraic system, and compared the result with an analytical solution.
That implementation was useful because it connected mathematical equations to executable code. However, it was designed for one particular problem.
Suppose we now want to solve:
- Steady heat conduction.
- Transient heat conduction.
- Convection–diffusion transport.
- Temperature transport in a flowing fluid.
- Momentum equations for incompressible flow.
- Pressure-correction equations.
- Transport equations for additional scalar quantities.
Implementing each problem independently would lead to duplicated code, inconsistent boundary treatment, and difficult maintenance.
A more scalable approach is to identify the operations that different equations share and organize them into reusable software components.
This is the purpose of a finite-volume framework.
A framework provides reusable structures for the mesh, fields, boundary conditions, fluxes, equation coefficients, linear solvers, and numerical diagnostics. Individual physical models then use these structures to define their equations.
The objective is not to build a production CFD package in one module. It is to develop an architecture that can grow without requiring the entire program to be rewritten every time a new equation is introduced.
2. Learning Objectives
By the end of this module, you should be able to:
- Explain the difference between a solver and a numerical framework.
- Design a simple mesh representation for a cell-centred finite-volume method.
- Represent scalar fields and boundary conditions in C++.
- Calculate face-based diffusion fluxes.
- Assemble a sparse linear system from finite-volume coefficients.
- Separate equation discretization from linear-system solution.
- Design interfaces that support future scalar and vector equations.
- Write tests for mesh geometry, fluxes, boundary conditions, and equation assembly.
- Identify the limitations of a one-dimensional prototype before extending it to multidimensional CFD.
3. What Should a Finite-Volume Framework Contain?
A finite-volume framework needs to represent both the computational geometry and the numerical equations defined on that geometry.
A useful conceptual architecture is:
Finite-Volume Framework
|
|-- Mesh
| |-- Cell centres
| |-- Cell volumes
| |-- Face centres
| |-- Face areas and normals
| |-- Owner and neighbour connectivity
|
|-- Fields
| |-- Scalar fields
| |-- Vector fields
| |-- Boundary values
|
|-- Boundary Conditions
| |-- Fixed value
| |-- Fixed normal gradient
| |-- Zero-gradient approximation
|
|-- Numerical Operators
| |-- Gradient
| |-- Divergence
| |-- Diffusion
| |-- Convection
| |-- Time derivative
|
|-- Equation Assembly
| |-- Coefficients
| |-- Source terms
| |-- Boundary contributions
|
|-- Linear Algebra
| |-- Sparse matrix
| |-- Linear solver
| |-- Residual calculation
|
|-- Diagnostics
| |-- Conservation
| |-- Convergence
| |-- Verification
|
|-- Input and Output
|-- Case settings
|-- Field output
|-- Post-processing
This architecture is a design target rather than a requirement to implement every component immediately.
The first version will remain one-dimensional. The important step is to keep the responsibilities separate so that the design can later support more general meshes.
4. The Mathematical Foundation
The finite-volume method begins with a conservation equation.
For a general scalar quantity , a common transport equation is
where:
- is density.
- is the transported scalar.
- is velocity.
- is the diffusion coefficient.
- is a source term per unit volume.
The terms represent transient storage, convection, diffusion, and sources.
Integrating over a control volume gives
Using the divergence theorem transforms the divergence terms into fluxes across the control-volume faces.
This equation is the mathematical reason that a finite-volume framework should represent faces explicitly.
A face-based representation allows the same geometrical information to be reused when calculating mass fluxes, diffusive fluxes, heat-transfer rates, and other transported quantities.
5. Cells, Faces, and Connectivity
A mesh is more than a collection of coordinates. It also describes how control volumes connect to one another.
5.1 Cells
Each cell stores geometric information such as:
- Cell centre.
- Cell volume.
- Connectivity to its faces.
For a one-dimensional uniform mesh of length with cells,
and the cell centre is
for zero-based indexing.
5.2 Faces
In a one-dimensional mesh, each cell has a west face and an east face.
An internal face is shared by two neighbouring cells. A boundary face belongs to only one computational cell.
In multiple dimensions, each face also requires an area and an oriented area vector.
The oriented area vector is commonly written as
where is face area and is the selected face-normal direction.
5.3 Owner and neighbour
A common mesh representation assigns each face an owner cell and, for internal faces, a neighbour cell.
- The owner is the cell associated with the selected face orientation.
- The neighbour is the cell on the opposite side of an internal face.
- A boundary face has an owner but no internal neighbour.
The exact owner–neighbour convention is a software design choice, but it must be consistent.
For an internal face, define the flux as positive from the owner toward the neighbour.
Then the contribution to the owner is the negative of the contribution to the neighbour when the cell equations use outward fluxes.
This shared-face convention is fundamental to discrete conservation.
6. Implement a Simple One-Dimensional Mesh
A minimal mesh can store the number of cells, the domain length, the cell width, and the cell centres.
#pragma once
#include <stdexcept>
#include <vector>
class Mesh1D {
public:
Mesh1D(double length, int cellCount)
: length_(length),
cellCount_(cellCount) {
if (length_ <= 0.0) {
throw std::invalid_argument(
"Length must be positive."
);
}
if (cellCount_ < 2) {
throw std::invalid_argument(
"At least two cells are required."
);
}
dx_ = length_ / cellCount_;
centres_.resize(cellCount_);
for (int i = 0; i < cellCount_; ++i) {
centres_[i] =
(static_cast<double>(i) + 0.5) * dx_;
}
}
int cellCount() const {
return cellCount_;
}
double length() const {
return length_;
}
double dx() const {
return dx_;
}
double cellCentre(int i) const {
return centres_.at(i);
}
private:
double length_;
int cellCount_;
double dx_;
std::vector<double> centres_;
};
This class performs only mesh-related tasks.
It does not know anything about temperature, pressure, velocity, or the diffusion equation.
That separation makes the mesh reusable across different physical models.
6.1 What is missing?
This mesh is sufficient for the first one-dimensional diffusion problem, but a multidimensional framework will eventually need:
- Face connectivity.
- Cell volumes.
- Face centres.
- Face area vectors.
- Boundary patch definitions.
- Neighbour relationships.
- Mesh quality information.
Do not add these structures merely to make the design look sophisticated. Introduce them when the numerical operators require them.
7. Represent Fields Independently of Equations
A field stores the numerical values of a physical quantity at the mesh locations.
For a cell-centred scalar field,
A simple implementation is:
#pragma once
#include <stdexcept>
#include <string>
#include <vector>
class ScalarField {
public:
ScalarField(
std::string name,
int cellCount,
double initialValue = 0.0
)
: name_(std::move(name)),
values_(cellCount, initialValue) {
if (cellCount <= 0) {
throw std::invalid_argument(
"Field size must be positive."
);
}
}
int size() const {
return static_cast<int>(values_.size());
}
double& operator[](int i) {
return values_.at(i);
}
double operator[](int i) const {
return values_.at(i);
}
const std::string& name() const {
return name_;
}
const std::vector<double>& values() const {
return values_;
}
private:
std::string name_;
std::vector<double> values_;
};
This class requires the <utility> header because it uses std::move. Add it to the includes:
#include <utility>
7.1 Why use a field class?
A field class can eventually support:
- Field names.
- Cell-centred values.
- Boundary values.
- Dimensions and units.
- Initialization.
- Interpolation.
- Arithmetic operations.
- Input and output.
- Field validation.
The current implementation is deliberately small. It does not yet implement dimensional analysis, vector fields, or boundary storage.
7.2 Scalar and vector fields
A scalar field stores one value per cell.
Examples include:
- Temperature.
- Pressure.
- Density.
- Turbulent kinetic energy.
- Species concentration.
A vector field stores a vector per cell.
Examples include:
- Velocity.
- Momentum.
- Vorticity.
In C++, a vector field could initially be represented by three scalar components, but a dedicated vector type often provides clearer mathematical operations.
The important design principle is to avoid tying the field representation to a particular governing equation.
8. Boundary Conditions as Explicit Objects
Boundary conditions are part of the mathematical problem and must be represented consistently in the numerical implementation.
Two common scalar boundary conditions are fixed value and fixed normal gradient.
8.1 Fixed-value boundary condition
A fixed-value condition prescribes the field at the boundary:
For heat conduction, this may represent a wall held at a known temperature.
8.2 Fixed-gradient boundary condition
A fixed-gradient condition prescribes the derivative normal to the boundary:
A zero-gradient condition is the special case
Zero gradient does not necessarily mean zero physical flux. For a diffusive flux
a zero normal gradient gives zero normal diffusive flux when is finite.
Other contributions, such as convective transport, may still cross the boundary.
8.3 A simple boundary-condition type
#pragma once
enum class BoundaryType {
FixedValue,
FixedGradient
};
struct ScalarBoundaryCondition {
BoundaryType type;
double value;
};
The meaning of value depends on the boundary type:
- For
FixedValue, it is the prescribed field value. - For
FixedGradient, it is the prescribed normal derivative.
This compact representation is suitable for a prototype.
A larger framework might use a polymorphic interface or a variant type, but additional abstraction is justified only when the boundary-condition behaviour becomes more complex.
9. Face-Based Diffusive Fluxes
A finite-volume method calculates transport through cell faces.
For diffusion, the flux density is
For a face with area vector , the integrated diffusive flux is approximately
The exact approximation depends on the mesh geometry and interpolation method.
9.1 One-dimensional internal face
For two adjacent cell centres separated by ,
Therefore, the diffusive flux density in the positive coordinate direction is
For a cross-sectional area ,
A single internal-face flux should be calculated once and then used with opposite signs in the two adjacent cell balances.
This is one of the most important design decisions in a conservative finite-volume implementation.
9.2 Boundary face
For a fixed-value boundary, the distance between the cell centre and boundary is on a uniform mesh.
The diffusive flux density at the west boundary is therefore approximated by
The corresponding expression at the east boundary uses the gradient between the last cell centre and the east boundary.
The direction and sign must follow the chosen face-normal convention.
9.3 Why fluxes should be reusable
A face-flux routine should not independently reconstruct slightly different fluxes for neighbouring cells.
If one cell uses a flux value that differs from the value used by its neighbour, local conservation can be lost.
For internal faces, shared flux calculations are therefore a natural foundation for the numerical architecture.
10. Equation Assembly as a Separate Operation
After discretizing a conservation equation, each cell contributes coefficients to a linear system.
A general scalar equation can be represented as
Here, the coefficients depend on the equation, the mesh, the numerical scheme, and the boundary conditions.
For a linear problem, assembly produces
A useful design separates two operations:
- Assembly: Calculate the matrix coefficients and right-hand side.
- Solution: Solve the assembled linear system.
This allows different numerical solvers to be used with the same assembled equation.
It also allows the same linear solver to be tested without repeatedly constructing the physical model.
10.1 Diffusion example
For the one-dimensional heat-conduction problem, the normalized coefficients are:
Interior cells:
Left boundary:
Right boundary:
The conductivity and mesh-spacing factors have been divided out because they are common to all terms in this constant-property, source-free example.
For a more general diffusion problem, the physical coefficients should be retained or normalized consistently.
10.2 Why not use one dense matrix?
A dense matrix stores every coefficient, including zeros.
For a mesh with unknowns, dense storage requires memory proportional to
Many finite-volume matrices contain only a small number of nonzero entries per row.
Sparse storage can reduce memory requirements substantially and is essential for large CFD systems.
For the first one-dimensional problem, a tridiagonal representation is sufficient. A general multidimensional framework will require a more flexible sparse-matrix representation.
11. Design a Linear-System Interface
The linear solver should receive an assembled system and return a numerical solution.
Conceptually, the interface is
solution = linearSolver.solve(system);
The assembly routine should not need to know whether the system is solved by:
- Thomas algorithm.
- Gaussian elimination.
- Jacobi iteration.
- Gauss–Seidel iteration.
- Conjugate gradient.
- Generalized minimal residual (GMRES).
- Another suitable direct or iterative method.
The appropriate method depends on the matrix properties and the size of the problem.
For example, the conjugate-gradient method is designed for symmetric positive-definite systems, while GMRES can be used for more general nonsymmetric systems.
Neither method is universally suitable for every CFD matrix.
11.1 Linear solver responsibilities
A reusable linear solver should eventually provide:
- Input dimension checks.
- A numerical solution.
- Residual calculation.
- Convergence information for iterative methods.
- Detection of breakdown or invalid numerical states.
- Iteration counts where applicable.
For iterative solvers, the residual vector is
A relative residual may be defined as
where is a small positive scale used to avoid division by zero.
This is one possible definition. Different solvers may use other normalizations, so the reported definition should be documented.
12. Complete Prototype: Assemble and Solve a Diffusion Equation
The following program demonstrates how the mesh, field, boundary conditions, equation assembly, and linear solver can be connected.
It is intentionally a compact prototype rather than a fully general framework. It keeps the diffusion equation and Thomas solver separate from the mesh and field structures.
Save it as main.cpp.
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
class Mesh1D {
public:
Mesh1D(double length, int cells)
: length_(length), cells_(cells) {
if (length_ <= 0.0 || cells_ < 2) {
throw std::invalid_argument(
"Invalid mesh dimensions."
);
}
dx_ = length_ / static_cast<double>(cells_);
centres_.resize(cells_);
for (int i = 0; i < cells_; ++i) {
centres_[i] =
(static_cast<double>(i) + 0.5) * dx_;
}
}
int cells() const {
return cells_;
}
double length() const {
return length_;
}
double dx() const {
return dx_;
}
double centre(int i) const {
return centres_.at(i);
}
private:
double length_;
int cells_;
double dx_;
std::vector<double> centres_;
};
class ScalarField {
public:
ScalarField(
std::string name,
int cells,
double initialValue = 0.0
)
: name_(std::move(name)),
values_(cells, initialValue) {
if (cells <= 0) {
throw std::invalid_argument(
"Field must contain at least one cell."
);
}
}
int size() const {
return static_cast<int>(values_.size());
}
double& operator[](int i) {
return values_.at(i);
}
double operator[](int i) const {
return values_.at(i);
}
const std::string& name() const {
return name_;
}
private:
std::string name_;
std::vector<double> values_;
};
enum class BoundaryType {
FixedValue
};
struct ScalarBoundaryCondition {
BoundaryType type;
double value;
};
struct TridiagonalSystem {
std::vector<double> lower;
std::vector<double> diagonal;
std::vector<double> upper;
std::vector<double> rhs;
explicit TridiagonalSystem(int n)
: lower(n, 0.0),
diagonal(n, 0.0),
upper(n, 0.0),
rhs(n, 0.0) {}
};
TridiagonalSystem assembleDiffusionEquation(
int cells,
const ScalarBoundaryCondition& west,
const ScalarBoundaryCondition& east
) {
if (west.type != BoundaryType::FixedValue ||
east.type != BoundaryType::FixedValue) {
throw std::invalid_argument(
"This assembly routine requires fixed values."
);
}
TridiagonalSystem system(cells);
// West boundary cell:
system.diagonal[0] = 3.0;
system.upper[0] = -1.0;
system.rhs[0] = 2.0 * west.value;
// Interior cells:
for (int i = 1; i < cells - 1; ++i) {
system.lower[i] = -1.0;
system.diagonal[i] = 2.0;
system.upper[i] = -1.0;
}
// East boundary cell:
system.lower[cells - 1] = -1.0;
system.diagonal[cells - 1] = 3.0;
system.rhs[cells - 1] = 2.0 * east.value;
return system;
}
std::vector<double> solveThomas(
const TridiagonalSystem& system
) {
const int n =
static_cast<int>(system.diagonal.size());
if (n < 2 ||
system.lower.size() != system.diagonal.size() ||
system.upper.size() != system.diagonal.size() ||
system.rhs.size() != system.diagonal.size()) {
throw std::invalid_argument(
"Invalid tridiagonal system."
);
}
std::vector<double> cPrime(n, 0.0);
std::vector<double> dPrime(n, 0.0);
double scale = 0.0;
for (double value : system.diagonal) {
scale = std::max(scale, std::abs(value));
}
if (scale == 0.0) {
throw std::runtime_error(
"The diagonal cannot be identically zero."
);
}
const double tolerance =
100.0 * std::numeric_limits<double>::epsilon()
* scale;
if (std::abs(system.diagonal[0]) <= tolerance) {
throw std::runtime_error(
"Unsafe first pivot."
);
}
cPrime[0] =
system.upper[0] / system.diagonal[0];
dPrime[0] =
system.rhs[0] / system.diagonal[0];
for (int i = 1; i < n; ++i) {
const double pivot =
system.diagonal[i]
- system.lower[i] * cPrime[i - 1];
if (std::abs(pivot) <= tolerance) {
throw std::runtime_error(
"Unsafe pivot in Thomas algorithm."
);
}
cPrime[i] = (i == n - 1)
? 0.0
: system.upper[i] / pivot;
dPrime[i] =
(system.rhs[i]
- system.lower[i] * dPrime[i - 1])
/ pivot;
}
std::vector<double> solution(n, 0.0);
solution[n - 1] = dPrime[n - 1];
for (int i = n - 2; i >= 0; --i) {
solution[i] =
dPrime[i] - cPrime[i] * solution[i + 1];
}
return solution;
}
double exactTemperature(
double x,
double length,
double leftTemperature,
double rightTemperature
) {
return leftTemperature
+ (rightTemperature - leftTemperature)
* x / length;
}
int main() {
try {
const double length = 1.0;
const double conductivity = 10.0;
const int cells = 40;
const ScalarBoundaryCondition west{
BoundaryType::FixedValue, 400.0
};
const ScalarBoundaryCondition east{
BoundaryType::FixedValue, 300.0
};
if (conductivity <= 0.0) {
throw std::invalid_argument(
"Conductivity must be positive."
);
}
const Mesh1D mesh(length, cells);
ScalarField temperature(
"temperature", cells, 0.0
);
const TridiagonalSystem system =
assembleDiffusionEquation(
cells, west, east
);
const std::vector<double> solution =
solveThomas(system);
for (int i = 0; i < cells; ++i) {
temperature[i] = solution[i];
}
std::ofstream output("solution.csv");
if (!output) {
throw std::runtime_error(
"Could not open solution.csv."
);
}
output
<< "x,T_numerical,T_exact,absolute_error\n"
<< std::setprecision(12);
double maximumError = 0.0;
for (int i = 0; i < cells; ++i) {
const double x = mesh.centre(i);
const double exact = exactTemperature(
x,
length,
west.value,
east.value
);
const double error =
std::abs(temperature[i] - exact);
maximumError =
std::max(maximumError, error);
output << x << ","
<< temperature[i] << ","
<< exact << ","
<< error << "\n";
}
std::cout
<< "Finite-volume diffusion prototype\n"
<< "Cells: " << cells << "\n"
<< "Cell width: " << mesh.dx() << "\n"
<< "Maximum absolute error: "
<< maximumError << "\n"
<< "Results written to solution.csv\n";
}
catch (const std::exception& error) {
std::cerr << "Error: "
<< error.what() << "\n";
return 1;
}
return 0;
}
12.1 Required header
The code uses std::numeric_limits, so include:
#include <limits>
This header is required for the code to compile.
12.2 Compile and run
Using a C++17-compatible compiler:
g++ -std=c++17 -O2 -Wall -Wextra -pedantic main.cpp -o fv_prototype
Run the executable:
./fv_prototype
The program writes solution.csv.
12.3 What does this implementation demonstrate?
The program shows how the main responsibilities can be separated:
Mesh1Dstores the geometry.ScalarFieldstores the cell-centred values.ScalarBoundaryConditionrepresents the prescribed boundary values.assembleDiffusionEquationcreates the discrete system.solveThomassolves the algebraic equations.exactTemperatureprovides the verification reference.maincoordinates the workflow and writes results.
The prototype is intentionally restricted. The boundary-condition type currently supports fixed values only, and the equation assembly is specific to the one-dimensional constant-property diffusion problem.
The next stage is to generalize the numerical operators without losing the ability to verify each change.
13. Improve the Linear-System Design
The tridiagonal structure is useful for a one-dimensional mesh, but multidimensional finite-volume systems generally require sparse matrices with more than three nonzero diagonals.
A scalable design should distinguish between:
- The mathematical equation.
- The storage format of its coefficients.
- The algorithm used to solve the system.
For example, a future interface might look conceptually like this:
class LinearSystem {
public:
void addCoefficient(
int row,
int column,
double value
);
void addSource(
int row,
double value
);
std::vector<double> solve() const;
};
This is an interface sketch, not a complete implementation.
For a large CFD calculation, the matrix would usually use a sparse representation rather than a dense two-dimensional array.
The framework should also provide a documented way to calculate residuals and check that the returned solution has the expected dimensions.
14. Test the Framework Components
Testing each component separately makes numerical errors easier to locate.
14.1 Mesh tests
Check that:
- The number of cells is correct.
- The domain length is positive.
- Cell centres lie inside the domain.
- The distance between consecutive centres is .
- Invalid cell indices are rejected.
For a uniform mesh, the first cell centre should be
and the last cell centre should be
14.2 Field tests
Check that:
- The field contains the requested number of values.
- Initialization sets all values correctly.
- Accessing an invalid index is rejected.
- The field name is preserved.
14.3 Linear-solver tests
For a known matrix and solution, construct the right-hand side and check whether the solver recovers the expected solution.
For example,
The known solution is
A solver test should check both the numerical values and the algebraic residual.
14.4 Equation-assembly tests
For the diffusion problem, verify that:
- The interior coefficients have the correct signs.
- The boundary coefficients use the half-cell distance.
- The source vector includes the prescribed boundary contributions.
- The matrix dimensions match the number of unknowns.
14.5 Integration tests
Finally, run the complete solver and compare the numerical result with the analytical solution.
A collection of unit and integration tests helps detect regressions when the framework evolves.
15. Conservation Must Guide the Design
Finite-volume methods are attractive because they can enforce conservation through shared face fluxes.
Consider an internal face shared by cells and .
Let the flux be positive from toward .
The contribution to the owner-cell balance is
when fluxes are defined as outward from the owner, while the contribution to the neighbour-cell balance is
The two contributions cancel when the cell equations are summed over the domain.
Consequently, internal-face transfers do not create or destroy the conserved quantity globally.
Only boundary fluxes, source terms, and transient storage contribute to the overall balance.
This property is preserved only if the same numerical face flux is used consistently in both neighbouring equations.
15.1 A design implication
For a multidimensional framework, face fluxes should be calculated and stored, or otherwise shared consistently, rather than being reconstructed independently for every cell.
This becomes particularly important for:
- Mass fluxes.
- Energy fluxes.
- Species transport.
- Multiphase mass transfer.
- Pressure–velocity coupling.
A well-designed data model should make inconsistent internal fluxes difficult to introduce accidentally.
16. How This Architecture Connects to OpenFOAM
OpenFOAM provides a useful example of a mature finite-volume framework.
Its architecture includes mesh representations, volume and surface fields, boundary patches, discretization operators, equation assembly, and linear solvers.
The precise implementation differs from the prototype in this module, but the conceptual responsibilities are related.
16.1 Mesh and fields
OpenFOAM distinguishes cell-centred volume fields from face-centred surface fields.
Examples include:
volScalarFieldfor cell-centred scalar quantities.volVectorFieldfor cell-centred vector quantities.surfaceScalarFieldfor scalar quantities defined on mesh faces.
These representations support the field and face-flux operations used in finite-volume discretization.
16.2 Diffusion operators
A diffusion term may be represented using an operator such as
fvm::laplacian(kappa, T)
where the exact dimensions and interpretation of kappa depend on the equation being assembled.
The fvm family generally constructs implicit finite-volume contributions.
By contrast, fvc operators generally evaluate explicit field operations.
For example:
fvc::grad(p)
calculates a pressure-gradient field.
These examples are illustrative. Their validity in a specific application depends on the field types, dimensions, and OpenFOAM version.
16.3 Why learn both approaches?
Using OpenFOAM helps solve complex engineering problems efficiently.
Implementing simplified operators independently helps explain what those operations do numerically.
The objective of a personal framework is not necessarily to reproduce all of OpenFOAM. It is to understand the numerical principles and create a small, testable environment in which those principles can be explored.
17. Development Exercises
Use these exercises to extend the prototype.
Exercise 1: Add a zero-gradient boundary condition
Extend the boundary-condition representation to include a prescribed normal gradient.
Derive the boundary flux and coefficient contributions before implementing them.
For a zero-gradient boundary in a pure diffusion problem, the normal diffusive flux should be zero.
Exercise 2: Add a source term
Extend the steady diffusion equation to include a source:
Be explicit about the sign convention for the source term and whether it is defined per unit volume or as an integrated cell contribution.
Verify the implementation using a manufactured solution.
Exercise 3: Add nonuniform cell spacing
Modify the mesh so that adjacent cell centres are not necessarily separated by the same distance.
Update the diffusion conductances using the actual distance between cell centres.
Do not assume that every face gradient can be calculated using a single global .
Exercise 4: Add a general sparse matrix
Replace the tridiagonal-specific system with a sparse representation.
Keep the equation assembly separate from the linear solver.
Exercise 5: Add a mesh-refinement driver
Write a script that runs the same case at several resolutions and collects:
- Cell count.
- Error norms.
- Runtime.
- Conservation error.
Generate a convergence plot automatically.
Exercise 6: Add a transient scalar equation
Introduce a time derivative and store the solution at the previous time level.
For an implicit time discretization, the transient term contributes to the diagonal and source vector.
Verify the transient solver against a suitable analytical or manufactured solution.
18. Common Architectural Mistakes
Mistake 1: Building one giant solver class
Putting the mesh, physical model, equation assembly, linear solver, and file output into a single class creates tight coupling.
Better practice: Give each component a clear responsibility.
Mistake 2: Creating abstractions before they are needed
A complicated inheritance hierarchy can make a small solver harder to understand.
Better practice: Begin with simple classes and introduce more general interfaces when multiple use cases justify them.
Mistake 3: Ignoring face orientation
Incorrect normal directions or inconsistent flux signs can destroy conservation.
Better practice: Define a clear face orientation and document whether fluxes are positive outward or along the selected face normal.
Mistake 4: Treating boundary conditions as post-processing
Boundary conditions influence the discrete equations and must be included consistently in equation assembly.
Better practice: Design boundary handling as part of the discretization workflow.
Mistake 5: Hard-coding every numerical coefficient
Hard-coded coefficients make the program difficult to extend to nonuniform meshes, variable properties, and other physical models.
Better practice: Calculate coefficients from the mesh, physical properties, and numerical scheme.
Mistake 6: Testing only the complete program
If the final solution is incorrect, it can be difficult to determine whether the error originates in the mesh, boundary treatment, assembly, or linear solver.
Better practice: Test individual components and then test their integration.
Mistake 7: Assuming a reusable framework is automatically accurate
Good software architecture cannot compensate for an incorrect mathematical formulation.
Better practice: Continue to derive equations, verify numerical operators, and compare against known solutions.
19. Key Takeaways
- A finite-volume framework separates common numerical infrastructure from individual physical models.
- Mesh geometry and connectivity are distinct from field values.
- Face-based fluxes provide the foundation for local and global conservation.
- Boundary conditions must be represented consistently with the location of the unknowns.
- Equation assembly and linear-system solution should be separate operations.
- A tridiagonal solver is suitable for the one-dimensional prototype but does not scale directly to general multidimensional matrices.
- Unit tests, integration tests, analytical comparisons, and conservation checks should be part of the development workflow.
- OpenFOAM demonstrates how mesh, fields, operators, and solvers can be combined in a mature finite-volume framework.
- A personal framework should evolve incrementally, with each new capability verified before further complexity is introduced.
20. What Comes Next?
The next step is to implement convection as a reusable finite-volume operator.
Convection introduces additional numerical choices because transported quantities depend on the direction of flow and on how face values are reconstructed.
A suitable next module is:
Module 12: Implementing Convection and Diffusion Operators in C++
It can extend this framework with:
- Face interpolation.
- Diffusive conductances.
- Convective mass fluxes.
- Central differencing.
- First-order upwind discretization.
- Combined convection–diffusion equations.
- Peclet-number analysis.
- Boundedness and numerical-diffusion tests.
This will move the project from a verified diffusion prototype toward a reusable transport solver and establish the numerical building blocks needed for more advanced CFD applications.