Module 12: Implementing Convection and Diffusion Operators in C++
Derive and implement finite-volume convection and diffusion operators in C++, compare central and upwind schemes, assemble a linear system, and verify the numerical solution.
1. Introduction
In Module 11, we developed the architecture of a finite-volume CFD framework. We introduced meshes, scalar fields, boundary conditions, face-based fluxes, equation assembly, and linear-system interfaces.
The next step is to implement two of the most important spatial operators in computational fluid dynamics:
- Diffusion, which transports a quantity down its gradient.
- Convection, which transports a quantity with the moving fluid.
Together, these operators appear in equations for temperature, species concentration, momentum, turbulence quantities, and many other transported fields.
For example, the steady convection–diffusion equation for a scalar field is
where:
- is the transported scalar.
- is the fluid density.
- is the velocity vector.
- is the diffusion coefficient.
- is a volumetric source term.
The objective of this module is to transform this equation into a working C++ solver while understanding every numerical step.
By the end, you should be able to:
- Derive a finite-volume convection–diffusion equation.
- Calculate convective and diffusive face fluxes.
- Implement central-difference and upwind interpolation.
- Assemble a tridiagonal linear system.
- Solve the system using the Thomas algorithm.
- Compare numerical solutions with an analytical benchmark.
- Identify numerical diffusion, boundedness problems, and implementation errors.
2. Physical interpretation of convection and diffusion
2.1 Convection
Convection transports a quantity because the fluid itself is moving.
Imagine a warm fluid entering a cold channel. The fluid carries its thermal energy downstream. The transport rate depends on the fluid velocity, density, and transported quantity.
For a one-dimensional flow through a cross-sectional area , the convective flux of a scalar is
where is the velocity in the streamwise direction.
For a temperature field, the corresponding convective energy transport also involves the fluid’s heat capacity. The equation above is the general scalar-transport form, with the appropriate definition of and its coefficients.
If the velocity is zero, there is no convective transport through the stationary fluid.
2.2 Diffusion
Diffusion transports a quantity because of spatial gradients.
For heat conduction, Fourier’s law states
where is the thermal conductivity and is temperature.
For a general scalar, the diffusive flux density is
The negative sign indicates that diffusion acts against the gradient.
In one dimension, the diffusive transport rate through an area is
If increases in the positive direction, then is positive and the diffusive flux is directed in the negative direction.
2.3 Total transport flux
Define the total flux in the positive direction as
where
is the mass flow rate through the face.
For steady transport without sources, conservation requires
Therefore,
For constant , , and , this becomes
This equation describes the competition between convection and diffusion.
3. From the differential equation to a finite-volume equation
The finite-volume method starts by integrating the conservation equation over a control volume.
For a one-dimensional cell extending from its west face to its east face ,
Applying the fundamental theorem of calculus gives
where and are the total fluxes through the east and west faces.
This equation has a direct physical interpretation:
The net flux leaving a steady control volume must be zero when there are no sources or sinks.
For a cell-centred finite-volume method, the cell value is stored at the cell centre, while fluxes are evaluated at its faces.
For cell , with west neighbour and east neighbour ,
The central numerical task is to express both face fluxes using the unknown cell-centred values.
3.1 Cell-centred mesh
Consider a uniform one-dimensional domain of length divided into cells.
The cell width is
The centre of cell is located at
for .
The scalar values are
The west and east boundary values are denoted by and .
The distance from a boundary face to the adjacent cell centre is , whereas the distance between neighbouring cell centres is .
This distinction is essential when calculating diffusive fluxes at boundaries.
4. Discretizing the diffusive flux
Consider an internal face between cells and .
Using a linear approximation to the gradient,
The diffusive flux at this face is
Define the diffusion conductance
Then
The conductance measures the strength of diffusion across the face.
A large conductance can result from a large diffusion coefficient or face area, or from a small distance between cell centres.
4.1 Diffusion at the boundaries
For a fixed-value boundary, the distance between the boundary face and the adjacent cell centre is .
The boundary conductance is therefore
or
for a uniform grid with constant properties.
At the west boundary, the total flux is
At the east boundary, it is
These expressions use the prescribed boundary value for the convective flux at the boundary face and a half-cell gradient for diffusion.
Important: A fixed-value condition specifies the scalar value at the boundary face. It is not the same as setting the first or last cell-centre value equal to that boundary value.
5. Discretizing the convective flux
The convective flux through a face is
The scalar value must be estimated from the neighbouring cell values. This is where the choice of numerical scheme enters.
Two foundational choices are central differencing and first-order upwind differencing.
5.1 Central differencing
Central differencing approximates the face value by linear interpolation.
For a uniform grid,
The convective flux becomes
Combining convection and diffusion gives
Rearranging,
Define the face coefficients
Then
Central differencing is second-order accurate for smooth fields on a uniform grid, but it may produce oscillations when convection dominates diffusion.
5.2 First-order upwind differencing
Upwind differencing selects the scalar value from the upstream side of the face.
For positive flow, , the fluid moves from west to east. The upstream value is :
Therefore,
or
The coefficients are
For negative flow, the upstream cell is on the east side, so . The corresponding flux is
The implementation must therefore account for the direction of flow rather than assuming that velocity is always positive.
5.3 Comparing the schemes
| Property | Central differencing | First-order upwind |
|---|---|---|
| Face value | Linear interpolation | Upstream cell value |
| Accuracy on a uniform grid | Second order for smooth fields | First order |
| Numerical diffusion | Usually lower | Usually higher |
| Robustness in convection-dominated flows | Can oscillate | Generally more robust |
| Main limitation | May lose boundedness | Can smear gradients |
Neither scheme is universally best. The appropriate choice depends on the physics, mesh resolution, desired accuracy, and stability requirements.
6. The cell Peclet number
The relative strength of convection and diffusion can be measured using the cell Peclet number:
For constant properties and positive velocity,
This dimensionless number helps explain the behaviour of convection–diffusion schemes.
- If is small, diffusion is relatively strong.
- If is large, convection is relatively strong.
- If , the equation contains no convection.
For the standard one-dimensional, uniform-grid central-difference finite-volume formulation with constant coefficients, the internal off-diagonal coefficients remain non-negative in the conventional coefficient form when
When this condition is violated, central differencing can lose the coefficient properties associated with bounded solutions and may produce nonphysical oscillations.
This is a scheme-specific criterion, not a universal stability condition for every CFD discretization.
Upwind differencing is more robust for large cell Peclet numbers, but its additional numerical diffusion can reduce accuracy.
7. Deriving the discrete linear system
The finite-volume equation for each cell is
For an internal face, write the total flux as
The exact values of and depend on the chosen convection scheme.
For a cell-centred mesh with fixed-value boundary conditions, assembling all face fluxes produces a linear system:
For a one-dimensional nearest-neighbour discretization, the matrix is tridiagonal:
Here:
- are diagonal coefficients.
- are lower-diagonal coefficients.
- are upper-diagonal coefficients.
- contains contributions from prescribed boundary values and any source terms.
Because each internal face is shared by two cells, its flux contributes with opposite signs to the neighbouring cell equations. This is how finite volume preserves local conservation.
7.1 Internal-face assembly
Suppose an internal face lies between cells and and its flux is
The flux contributes positively to the east face of cell :
It contributes negatively to the west face of cell :
The same numerical flux is used on both sides of the face. This is a key conservation principle.
7.2 Boundary assembly
For the west boundary,
Because the cell equation contains , the matrix diagonal receives and the right-hand side receives
For the east boundary,
The final cell equation therefore receives a diagonal contribution of and a right-hand-side contribution
These terms are included in the C++ implementation below.
8. Building the C++ solver
We will implement a standalone one-dimensional solver with the following features:
- Uniform, cell-centred mesh.
- Constant density, velocity, diffusion coefficient, and cross-sectional area.
- Steady convection–diffusion with no volumetric source.
- Fixed scalar values at both boundary faces.
- Central-difference or first-order upwind interpolation.
- Tridiagonal matrix assembly.
- Thomas algorithm for the linear system.
- Comparison with an analytical solution.
- CSV output for plotting and verification.
The implementation deliberately separates the numerical operations so that each part can later become a component in a larger CFD framework.
8.1 Governing equation and assumptions
We solve
with
and
The mass flow rate and the diffusion coefficient are constant.
The analytical solution for nonzero velocity is
where
is the domain Peclet number.
When , the solution reduces to a linear profile:
The analytical solution is useful for checking the implementation. A correct numerical method should approach it as the mesh is refined, subject to the accuracy of the selected scheme.
8.2 Complete C++ implementation
Save the following code as convection_diffusion_1d.cpp.
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>
enum class ConvectionScheme
{
Central,
Upwind
};
struct Parameters
{
int cells = 100;
double length = 1.0;
double area = 1.0;
double density = 1.0;
double velocity = 0.5;
double diffusivity = 0.1;
double phiLeft = 1.0;
double phiRight = 0.0;
ConvectionScheme scheme = ConvectionScheme::Upwind;
};
struct LinearSystem
{
// lower[i] is A(i, i-1); lower[0] is unused.
// upper[i] is A(i, i+1); upper[N-1] is unused.
std::vector<double> lower;
std::vector<double> diagonal;
std::vector<double> upper;
std::vector<double> rhs;
};
struct FaceCoefficients
{
double left;
double right;
};
void validate(const Parameters& p)
{
if (p.cells < 2)
{
throw std::invalid_argument(
"At least two cells are required.");
}
if (!(p.length > 0.0) ||
!(p.area > 0.0) ||
!(p.density > 0.0) ||
!(p.diffusivity > 0.0))
{
throw std::invalid_argument(
"Length, area, density, and diffusivity "
"must be positive.");
}
if (!std::isfinite(p.velocity) ||
!std::isfinite(p.phiLeft) ||
!std::isfinite(p.phiRight))
{
throw std::invalid_argument(
"Velocity and boundary values must be finite.");
}
}
FaceCoefficients internalFaceCoefficients(
double massFlux,
double diffusionConductance,
ConvectionScheme scheme)
{
const double F = massFlux;
const double D = diffusionConductance;
if (scheme == ConvectionScheme::Central)
{
// J = F * (phiL + phiR) / 2
// + D * (phiL - phiR)
return {
D + 0.5 * F,
0.5 * F - D
};
}
// First-order upwind interpolation.
if (F >= 0.0)
{
// Flow travels from left to right:
// phi_face = phi_left.
return {
D + F,
-D
};
}
// Flow travels from right to left:
// phi_face = phi_right.
return {
D,
F - D
};
}
LinearSystem assemble(const Parameters& p)
{
validate(p);
const int N = p.cells;
const double dx = p.length / N;
// Positive F means flow in the positive x direction.
const double F =
p.density * p.velocity * p.area;
// Internal face conductance.
const double D =
p.diffusivity * p.area / dx;
// Boundary face conductance:
// boundary-to-cell-centre distance is dx / 2.
const double Db = 2.0 * D;
LinearSystem system{
std::vector<double>(N, 0.0),
std::vector<double>(N, 0.0),
std::vector<double>(N, 0.0),
std::vector<double>(N, 0.0)
};
// West boundary:
//
// J_w = -Db * phi_1 + (F + Db) * phiLeft
//
// The cell equation contains -J_w.
system.diagonal[0] += Db;
system.rhs[0] += (F + Db) * p.phiLeft;
// East boundary:
//
// J_e = Db * phi_N + (F - Db) * phiRight
//
// The cell equation contains +J_e.
system.diagonal[N - 1] += Db;
system.rhs[N - 1] +=
(Db - F) * p.phiRight;
// Assemble each internal face exactly once.
for (int i = 0; i < N - 1; ++i)
{
const FaceCoefficients c =
internalFaceCoefficients(
F, D, p.scheme);
// Flux at the face between cell i and cell i+1:
//
// J_f = c.left * phi_i
// + c.right * phi_(i+1)
// Add the flux to the east face of cell i.
system.diagonal[i] += c.left;
system.upper[i] += c.right;
// Subtract the same flux from the west face
// of cell i+1.
system.lower[i + 1] -= c.left;
system.diagonal[i + 1] -= c.right;
}
return system;
}
std::vector<double> solveThomas(LinearSystem system)
{
const int N =
static_cast<int>(system.diagonal.size());
if (N == 0)
{
throw std::invalid_argument(
"Cannot solve an empty linear system.");
}
// Forward elimination.
for (int i = 1; i < N; ++i)
{
const double pivot =
system.diagonal[i - 1];
if (std::abs(pivot) <
100.0 * std::numeric_limits<double>::epsilon())
{
throw std::runtime_error(
"Near-zero pivot in Thomas algorithm.");
}
const double factor =
system.lower[i] / pivot;
system.diagonal[i] -=
factor * system.upper[i - 1];
system.rhs[i] -=
factor * system.rhs[i - 1];
}
const double finalPivot =
system.diagonal[N - 1];
if (std::abs(finalPivot) <
100.0 * std::numeric_limits<double>::epsilon())
{
throw std::runtime_error(
"Near-zero final pivot in Thomas algorithm.");
}
// Back substitution.
std::vector<double> phi(N, 0.0);
phi[N - 1] =
system.rhs[N - 1] /
system.diagonal[N - 1];
for (int i = N - 2; i >= 0; --i)
{
phi[i] =
(system.rhs[i] -
system.upper[i] * phi[i + 1]) /
system.diagonal[i];
}
return phi;
}
double analyticalSolution(
double x,
const Parameters& p)
{
const double Pe =
p.density * p.velocity * p.length /
p.diffusivity;
const double deltaPhi =
p.phiRight - p.phiLeft;
if (std::abs(Pe) < 1.0e-8)
{
return p.phiLeft +
deltaPhi * x / p.length;
}
// expm1(z) evaluates exp(z) - 1 more accurately
// when z is close to zero.
const double numerator =
std::expm1(Pe * x / p.length);
const double denominator =
std::expm1(Pe);
return p.phiLeft +
deltaPhi * numerator / denominator;
}
void writeCSV(
const Parameters& p,
const std::vector<double>& phi,
const std::string& filename)
{
std::ofstream file(filename);
if (!file)
{
throw std::runtime_error(
"Could not open output file: " + filename);
}
file << "x,phi_numerical,phi_analytical,error\n";
file << std::setprecision(12);
const double dx = p.length / p.cells;
for (int i = 0; i < p.cells; ++i)
{
const double x =
(i + 0.5) * dx;
const double exact =
analyticalSolution(x, p);
const double error =
phi[i] - exact;
file << x << ','
<< phi[i] << ','
<< exact << ','
<< error << '\n';
}
}
int main(int argc, char* argv[])
{
try
{
Parameters p;
// Usage:
// ./convection_diffusion_1d [cells] [central|upwind]
if (argc >= 2)
{
p.cells = std::stoi(argv[1]);
}
if (argc >= 3)
{
const std::string scheme = argv[2];
if (scheme == "central")
{
p.scheme = ConvectionScheme::Central;
}
else if (scheme == "upwind")
{
p.scheme = ConvectionScheme::Upwind;
}
else
{
throw std::invalid_argument(
"Scheme must be 'central' or 'upwind'.");
}
}
validate(p);
const LinearSystem system = assemble(p);
const std::vector<double> phi =
solveThomas(system);
const double dx =
p.length / p.cells;
double maxError = 0.0;
double sumSquaredError = 0.0;
for (int i = 0; i < p.cells; ++i)
{
const double x =
(i + 0.5) * dx;
const double exact =
analyticalSolution(x, p);
const double error =
phi[i] - exact;
maxError = std::max(
maxError, std::abs(error));
sumSquaredError += error * error;
}
const double rmsError =
std::sqrt(
sumSquaredError / p.cells);
const double domainPe =
p.density * p.velocity * p.length /
p.diffusivity;
const double cellPe =
p.density * p.velocity * dx /
p.diffusivity;
writeCSV(p, phi, "convection_diffusion.csv");
std::cout << std::setprecision(8);
std::cout << "1D steady convection-diffusion solver\n";
std::cout << "Cells: " << p.cells << '\n';
std::cout << "Scheme: "
<< (p.scheme == ConvectionScheme::Central
? "central"
: "upwind")
<< '\n';
std::cout << "Domain Peclet number: "
<< domainPe << '\n';
std::cout << "Cell Peclet number: "
<< cellPe << '\n';
std::cout << "Maximum absolute error: "
<< maxError << '\n';
std::cout << "RMS error: "
<< rmsError << '\n';
std::cout
<< "Wrote convection_diffusion.csv\n";
return 0;
}
catch (const std::exception& e)
{
std::cerr << "Error: " << e.what() << '\n';
return 1;
}
}
8.3 Compile and run
With a C++17-compatible compiler, compile using:
g++ -std=c++17 -O2 -Wall -Wextra -pedantic \
convection_diffusion_1d.cpp \
-o convection_diffusion_1d
Run the upwind scheme on 100 cells:
./convection_diffusion_1d 100 upwind
Run the central-difference scheme on the same mesh:
./convection_diffusion_1d 100 central
On Windows with MinGW, the commands are similar, but the executable is typically named convection_diffusion_1d.exe.
The solver writes a CSV file containing the cell-centre coordinates, numerical solution, analytical solution, and pointwise error.
Expected behaviour: both schemes should produce finite results for the default parameters. Their errors will differ because they use different approximations for convective transport. Do not assume that the error must decrease by exactly a factor of two when the cell count doubles; the observed convergence depends on the scheme, boundary treatment, and mesh resolution.
9. Understanding the implementation
9.1 Why are the face coefficients returned by a function?
The function internalFaceCoefficients() represents the numerical flux independently of the matrix assembly.
For central differencing,
For upwind differencing with positive flow,
Both schemes return two coefficients, but those coefficients differ because the approximation of the convective face value differs.
This design allows another scheme to be introduced without rewriting the entire solver.
For example, a future implementation could add a bounded higher-resolution scheme while leaving the mesh, boundary treatment, and linear solver unchanged.
9.2 Why is each internal face assembled once?
An internal face connects two neighbouring control volumes. The flux leaving one cell enters the other cell with the opposite sign.
If the flux is
then the left cell receives in its east-face contribution, while the right cell receives in its west-face contribution.
The assembly code uses exactly this relationship.
Computing one shared flux expression prevents the two neighbouring cells from using inconsistent versions of the same physical transfer.
9.3 Why is the boundary conductance doubled?
The distance from the boundary face to the adjacent cell centre is half the normal cell width.
The diffusive conductance is inversely proportional to the distance:
Using rather than at these faces would underestimate the diffusive boundary contribution for this uniform, cell-centred discretization.
9.4 Why does the Thomas algorithm work here?
The one-dimensional discretization connects each cell only to its immediate neighbours. The resulting matrix is tridiagonal.
The Thomas algorithm solves this system using forward elimination followed by back substitution.
Its computational cost is proportional to the number of cells, , rather than the cost associated with a generic dense direct solve.
The method is appropriate for this tridiagonal system when its pivots remain nonzero. It is not a general replacement for the sparse linear solvers required by large multidimensional CFD problems.
10. Verification against the analytical solution
Verification asks whether the numerical implementation correctly solves the mathematical model that was specified.
For this module, the analytical solution gives us an independent reference for the discrete results.
10.1 Error metrics
Let be the numerical solution and the analytical solution at the centre of cell .
The pointwise error is
The maximum absolute error is
The root-mean-square error is
These measures capture different aspects of the discrepancy. The maximum error highlights the largest local deviation, while the RMS error measures the overall magnitude of the error across the cells.
10.2 Mesh-refinement study
Run each scheme with several cell counts:
./convection_diffusion_1d 25 upwind
./convection_diffusion_1d 50 upwind
./convection_diffusion_1d 100 upwind
./convection_diffusion_1d 200 upwind
Repeat with central differencing:
./convection_diffusion_1d 25 central
./convection_diffusion_1d 50 central
./convection_diffusion_1d 100 central
./convection_diffusion_1d 200 central
Record the RMS error from each run.
A typical convergence table is:
| Cells | Cell width | RMS error |
|---|---|---|
| 25 | Measure | |
| 50 | Measure | |
| 100 | Measure | |
| 200 | Measure |
Replace “Measure” with the values reported by your actual runs. The values should be measured rather than assumed.
For sufficiently smooth solutions and a properly resolved mesh, first-order upwind is expected to show approximately first-order spatial convergence, while central differencing can show approximately second-order spatial convergence under suitable conditions. Boundary treatment, Peclet number, and solution regularity can affect the observed rate.
10.3 Estimating the observed order
Suppose the mesh spacing is reduced by a factor of two, and the errors on the coarse and fine meshes are and .
The observed order can be estimated as
For example, if the error decreases by approximately a factor of two, the observed order is close to one. If it decreases by approximately a factor of four, the observed order is close to two.
This estimate is meaningful only when both meshes are in the asymptotic convergence range and the errors are not dominated by round-off or other effects.
10.4 Conservation check
For the source-free steady equation, the total flux should be constant throughout the domain:
The numerical flux should be evaluated using the same scheme and boundary treatment used during assembly.
A useful extension is to calculate the flux through every face and report
A large value of can indicate an error in flux evaluation, assembly, or the linear solve.
For a converged solution of the assembled system, flux imbalance should be small relative to the characteristic flux scale, subject to solver precision and the numerical conditioning of the problem.
11. Numerical diffusion and scheme behaviour
11.1 Why upwind can smear a solution
Upwind differencing uses the upstream cell value for the convective flux. This is robust, but it introduces additional numerical diffusion.
In a convection-dominated flow, that diffusion can broaden sharp gradients and make the computed field appear smoother than the physical solution.
For a smooth solution, the error should reduce with mesh refinement. However, a coarse mesh can obscure important features even when the linear system has been solved accurately.
11.2 Why central differencing can oscillate
Central differencing uses information from both sides of a face. It is less diffusive for smooth fields, but its coefficients can lose the properties needed to maintain bounded solutions when convection dominates diffusion.
This may produce overshoots or undershoots, such as values outside the range imposed by the boundary conditions.
An accurate linear-system solution does not guarantee a physically acceptable discretized solution. The discretization itself must also be appropriate.
11.3 What about higher-order schemes?
Professional CFD solvers often use higher-resolution schemes designed to balance accuracy and boundedness.
Examples include:
- Total variation diminishing (TVD) schemes.
- Flux-limiter methods.
- Bounded linear-upwind schemes.
- Other higher-order reconstruction methods.
These schemes typically use additional information from neighbouring cells and apply limiting strategies to control nonphysical oscillations.
They are valuable when resolving steep gradients, wakes, shear layers, and transported interfaces, but their implementation is more involved than the two foundational schemes in this module.
12. Practical testing strategy
A CFD implementation should be tested systematically rather than judged from one plausible-looking plot.
Test 1: Pure diffusion
Set
The analytical solution is linear. Both central differencing and upwind differencing reduce to the same internal diffusive flux formula.
Check whether the numerical profile approaches the linear analytical solution and whether the flux remains constant.
Test 2: Positive convection
Use
The flow travels from left to right. Verify that the upwind scheme selects the west-side cell value for internal convective faces.
Test 3: Negative convection
Use
The flow travels from right to left. Verify that the upwind scheme selects the east-side cell value.
This test is particularly useful for catching sign errors in the convective flux.
Test 4: Mesh refinement
Increase the number of cells while keeping the physical parameters unchanged.
Check whether the numerical solution approaches the analytical solution and whether the observed convergence rate is consistent with the scheme.
Test 5: Boundary conditions
Check that the boundary values are used at the boundary faces and that the half-cell distance is included in the diffusive boundary conductance.
Do not simply force the first and last cell-centre values to equal the boundary-face values. Those are different locations on a cell-centred mesh.
Test 6: Linear-system residual
After solving, evaluate the residual of the assembled system:
A small residual indicates that the discrete linear equations have been solved accurately. It does not, by itself, establish that the discretization is accurate or that the mathematical model represents a real physical system.
Test 7: Boundedness
For the selected boundary values, inspect the minimum and maximum numerical values.
For example, when both boundary values lie between zero and one, investigate any numerical values outside that range. Such behaviour can indicate a non-monotone discretization, a boundary treatment issue, or an implementation error.
Central differencing is not guaranteed to remain bounded for arbitrary cell Peclet numbers.
13. Connecting the implementation to OpenFOAM
The operators implemented here are simplified versions of the transport operators used in professional finite-volume solvers.
For a scalar field , a general transport equation may contain terms representing transient accumulation, convection, diffusion, and sources:
In OpenFOAM, operators are assembled using the finite-volume framework. For example, a schematic scalar transport equation may include expressions of the form:
fvm::ddt(rho, phi)
+ fvm::div(phiFlux, phi)
- fvm::laplacian(gamma, phi)
==
source;
This is illustrative rather than a complete, universally compilable equation. The field types, flux definitions, dimensions, solver setup, and boundary conditions must match the specific case. In particular, the name phi is often used for a face flux in OpenFOAM examples, so a scalar field and its flux should be given distinct names in actual code.
The key conceptual correspondence is:
| This module | Finite-volume solver concept |
|---|---|
internalFaceCoefficients() | Scheme-dependent face-flux discretization |
assemble() | Matrix and source-term assembly |
solveThomas() | Linear-system solution |
analyticalSolution() | Analytical benchmark |
| CSV errors | Verification and post-processing |
| Fixed-value face treatment | Boundary-condition contribution to the matrix |
The OpenFOAM implementation handles much more than this example: multidimensional meshes, non-orthogonal corrections, variable properties, coupled boundary conditions, parallel communication, sparse matrices, and a wide range of discretization schemes.
The purpose of building this small solver is to understand the numerical principles beneath those abstractions.
14. Common implementation mistakes
Mistake 1: Reversing the diffusive flux sign
The diffusive flux is
For an internal face,
Reversing this sign turns diffusion into anti-diffusion and can make the problem physically incorrect or numerically unstable.
Mistake 2: Using the wrong upwind cell
The upstream side depends on the sign of the mass flux , not on the cell index alone.
For positive , use the left cell. For negative , use the right cell.
Mistake 3: Using the wrong face distance
The distance between neighbouring cell centres is . The distance from a boundary face to its adjacent cell centre is .
The diffusive conductance must reflect the correct distance.
Mistake 4: Assembling a shared face twice
A shared internal face should contribute with opposite signs to its two neighbouring cell equations. Using inconsistent flux expressions on the two sides can destroy local conservation.
Mistake 5: Confusing solver convergence with numerical accuracy
A linear solver may produce a very small residual while the discretized solution remains inaccurate because the mesh is too coarse or the numerical scheme is unsuitable.
Check both algebraic convergence and discretization error.
Mistake 6: Trusting a plot without a benchmark
A smooth field is not proof of correctness. Compare the solution with an analytical or independently verified reference whenever possible.
Mistake 7: Ignoring units
The terms in the flux expression must be dimensionally consistent. For example, if is dimensionless, both and have units of mass per time when and use a compatible scalar diffusivity.
If represents temperature and is thermal conductivity, the diffusion coefficient and convective coefficient must instead be chosen consistently with the specific energy equation being solved.
15. Exercises
Work through the following exercises to develop a stronger understanding of the numerical method.
Exercise 1: Compare central and upwind schemes
Run both schemes with 100 cells using the default parameters.
Record the RMS error and compare the numerical profiles.
Explain why the two schemes produce different results even though they solve the same continuous equation.
Exercise 2: Change the cell Peclet number
Change the velocity from to while keeping the diffusivity unchanged.
Run the central and upwind schemes.
Determine the new cell Peclet number and inspect the results for overshoots or undershoots.
Exercise 3: Reverse the flow
Set the velocity to a negative value.
Confirm that the upwind scheme selects the correct upstream cell and explain how the boundary conditions interact with the reversed flow.
Exercise 4: Investigate numerical diffusion
Run the upwind scheme with 25, 50, 100, and 200 cells.
Plot the numerical and analytical solutions together. Describe how the numerical profile changes as the mesh is refined.
Exercise 5: Implement a source term
Extend the equation to include a constant source:
The finite-volume balance becomes
for a uniform volumetric source density .
Add the integrated source contribution to the right-hand side and derive the corresponding analytical solution for a simple test case.
Exercise 6: Add a zero-gradient boundary
Replace the fixed-value condition at the outlet with a zero-gradient condition:
Derive the resulting boundary-face flux and modify the matrix assembly. Be careful to distinguish the diffusive boundary contribution from the convective outflow contribution.
Exercise 7: Refactor the framework
Separate the implementation into classes or modules for:
- Mesh geometry.
- Scalar field storage.
- Convection schemes.
- Diffusion fluxes.
- Boundary conditions.
- Matrix assembly.
- Linear solvers.
- Verification and output.
The goal is to make it possible to add a new convection scheme without rewriting the mesh or linear solver.
16. Key takeaways
Convection and diffusion are fundamental building blocks of CFD. Their implementation requires more than writing down a differential equation: the equation must be integrated over control volumes, the face fluxes must be approximated, boundary conditions must be incorporated, and the resulting algebraic system must be solved.
The most important principles from this module are:
- Conservation comes first. Begin with the balance of fluxes through the control-volume faces.
- The face interpolation defines the scheme. Central and upwind differ in how the convective face value is estimated.
- Flow direction matters. An upwind scheme must select the upstream value according to the sign of the face mass flux.
- Boundary geometry matters. A cell-centred boundary face is half a cell width from the adjacent cell centre on a uniform grid.
- Assembly must preserve shared-face consistency. Each internal flux enters neighbouring equations with opposite signs.
- Accuracy must be verified. Compare against analytical solutions and perform mesh-refinement studies.
- A small solver is a learning instrument. It reveals the numerical structure that larger CFD software packages automate.
17. What’s next?
In Module 13, the natural next step is to develop higher-order convection schemes and flux limiters. First-order upwind is robust but diffusive, while central differencing can oscillate in convection-dominated problems. Higher-resolution schemes aim to improve accuracy without introducing unacceptable nonphysical oscillations.
The next module can build on the face-flux interface introduced here, add gradient reconstruction, and explore how numerical schemes balance accuracy, boundedness, and robustness.