Fortran Numerical Weather Prediction Models

High-performance computational models for operational-scale atmospheric simulation

Why Fortran for Numerical Weather Prediction?

Despite being one of the oldest programming languages, Fortran (FORmula TRANslation) remains the dominant language for operational numerical weather prediction (NWP) and climate modeling. Major centers like ECMWF, NCEP, UK Met Office, and Mรฉtรฉo-France all use Fortran for their core models.

๐Ÿš€ Performance

Fortran compilers produce highly optimized machine code. 5-20% faster than C/C++ for array-heavy numerical computations. Critical when running on supercomputers.

๐Ÿ“ Array Operations

Native multi-dimensional array syntax. Whole-array operations, slicing, and intrinsic functions designed for scientific computing from the ground up.

โšก Parallelization

Excellent support for OpenMP (shared memory) and MPI (distributed memory) parallelism. Modern Fortran includes coarrays for parallel programming.

๐Ÿ›๏ธ Legacy & Stability

Decades of optimized numerical libraries (BLAS, LAPACK, FFTW). Proven algorithms refined over 60+ years of scientific computing.

Real-World Usage

WRF (Weather Research and Forecasting), MPAS (Model for Prediction Across Scales), CAM (Community Atmosphere Model), and the ECMWF IFS are all written primarily in Fortran 90/95/2003/2008.

Setup Instructions

1. Install Fortran Compiler

We recommend gfortran (GNU Fortran compiler), which is free, open-source, and supports modern Fortran standards (2003, 2008, 2018).

Linux (Debian/Ubuntu):
sudo apt-get update
sudo apt-get install gfortran
Linux (Fedora/RHEL):
sudo dnf install gcc-gfortran
macOS (with Homebrew):
brew install gcc
Windows:
# Install MinGW-w64 which includes gfortran
# Or use Windows Subsystem for Linux (WSL)

2. Verify Installation

# Check gfortran version
gfortran --version
# Should show version 9.0 or higher (supports Fortran 2008)

3. Basic Compilation

Standard compilation command structure:

gfortran -o executable_name source_file.f90 [options]
# Common optimization flags:
-O3 # Maximum optimization
-march=native # Optimize for your CPU
-ffast-math # Aggressive math optimizations
-fopenmp # Enable OpenMP parallel processing

1Primitive Equations Model (3D)

Scientific Background

This model solves the full 3D primitive equations โ€” the fundamental equations governing atmospheric motion. It's based on the approach used in WRF (Weather Research and Forecasting Model), the most widely-used mesoscale NWP model globally.

Governing Equations

In pressure coordinates (p), the primitive equations are:

1. Momentum (u-component):\[\frac{\partial u}{\partial t} = -u\frac{\partial u}{\partial x} - v\frac{\partial u}{\partial y} - \omega\frac{\partial u}{\partial p} + fv - \frac{1}{\rho}\frac{\partial p'}{\partial x} + F_u\]
2. Momentum (v-component):\[\frac{\partial v}{\partial t} = -u\frac{\partial v}{\partial x} - v\frac{\partial v}{\partial y} - \omega\frac{\partial v}{\partial p} - fu - \frac{1}{\rho}\frac{\partial p'}{\partial y} + F_v\]
3. Hydrostatic equation:\[\frac{\partial \Phi}{\partial p} = -\frac{RT_v}{p}\]
4. Continuity (mass conservation):\[\frac{\partial u}{\partial x} + \frac{\partial v}{\partial y} + \frac{\partial \omega}{\partial p} = 0\]
5. Thermodynamic equation:\[\frac{\partial T}{\partial t} = -u\frac{\partial T}{\partial x} - v\frac{\partial T}{\partial y} - \omega\left(\frac{\partial T}{\partial p} - \frac{\kappa T}{p}\right) + \frac{Q}{c_p}\]

Model Features

Grid Configuration

  • 64ร—64 horizontal grid points
  • 20 vertical levels (ฯƒ-coordinates)
  • Arakawa C-grid (staggered)
  • 2000 km ร— 2000 km domain

Numerical Methods

  • 3rd-order Runge-Kutta time integration
  • Centered finite differences (space)
  • Semi-implicit scheme for stability
  • 60-second time step

Physics Parameterizations

  • Planetary boundary layer (YSU scheme)
  • Radiation (simplified LW/SW)
  • Microphysics (Kessler warm rain)
  • Surface fluxes (Monin-Obukhov)

Initial Conditions

  • Baroclinic wave perturbation
  • Midlatitude jet stream
  • Realistic temperature profile
  • Water vapor distribution

Compilation Instructions

# Basic compilation (no optimization)
gfortran -o primitive_equations primitive_equations.f90
# Optimized compilation (recommended)
gfortran -o primitive_equations primitive_equations.f90 -O3 -march=native
# With parallelization (if OpenMP directives added)
gfortran -o primitive_equations primitive_equations.f90 -O3 -fopenmp

How to Run

# Execute the compiled program
./primitive_equations
# Set number of OpenMP threads (if parallelized)
export OMP_NUM_THREADS=4
./primitive_equations

Expected Output

The model will:

  • Print domain configuration (grid size, spacing, time step)
  • Display initialization information
  • Output diagnostics every 20 time steps showing:
    • Integration time (hours)
    • Maximum wind speeds (u, v components)
    • Temperature range and extremes
    • Energy conservation metrics
  • Confirm successful completion with total integration time

Runtime: Approximately 1-5 minutes on a modern CPU (depends on optimization level). With parallelization, can be reduced to under 1 minute.

๐Ÿ“Š Output Files (if implemented)

Full versions would write netCDF or binary output files containing 3D fields of u, v, w, temperature, pressure, geopotential at each output time. These can be visualized with tools like NCL, Python (xarray), or VAPOR.

2Shallow Water Equations Model (2D)

Scientific Background

The shallow water equations are a simplified set of equations describing fluid motion in a thin layer. Despite their simplicity, they capture many essential atmospheric phenomena and are widely used for testing numerical methods, studying atmospheric waves, and teaching NWP fundamentals.

The Equations

On an f-plane (constant latitude), the shallow water equations are:

1. u-momentum:\[\frac{\partial u}{\partial t} - fv = -g\frac{\partial h}{\partial x} + F_x\]
2. v-momentum:\[\frac{\partial v}{\partial t} + fu = -g\frac{\partial h}{\partial y} + F_y\]
3. Continuity (mass):\[\frac{\partial h}{\partial t} = -\frac{\partial(hu)}{\partial x} - \frac{\partial(hv)}{\partial y}\]
where: u, v = horizontal velocities [m/s], h = fluid depth [m], f = Coriolis parameter [sโปยน], g = gravity [m/sยฒ]

Atmospheric Phenomena Captured

Geostrophic Adjustment

How an initially imbalanced flow adjusts to geostrophic equilibrium through emission of inertia-gravity waves

Rossby Waves

Planetary-scale waves fundamental to weather patterns. Responsible for meandering jet stream and blocking patterns.

Kelvin Waves

Coastally-trapped waves important in equatorial dynamics and tropical meteorology

Inertia-Gravity Waves

Fast waves that adjust pressure and velocity fields. Important for numerical stability considerations.

Model Configuration

Grid:
  • 128 ร— 128 horizontal points
  • 1000 km ร— 1000 km domain
  • ~7.8 km grid spacing
Numerics:
  • Leapfrog time integration
  • Centered finite differences
  • 60-second time step
  • Periodic boundary conditions
Physics:
  • ฮฒ-plane approximation (f = fโ‚€ + ฮฒy)
  • Mean depth Hโ‚€ = 1000 m
  • fโ‚€ = 10โปโด sโปยน (mid-latitude)
Initial Condition:
  • Geostrophically balanced vortex
  • Gaussian height anomaly
  • 100 m amplitude, 100 km radius

Compilation Instructions

# Standard compilation
gfortran -o shallow_water shallow_water.f90
# With optimization (recommended for faster execution)
gfortran -o shallow_water shallow_water.f90 -O3 -march=native -ffast-math
# Check for compilation errors/warnings
gfortran -o shallow_water shallow_water.f90 -Wall -Wextra

How to Run

# Execute the model
./shallow_water
# Output will print to terminal in real-time

Expected Output

The model outputs:

  • Header: Grid size, domain dimensions, time step, integration length
  • Progress updates every 100 time steps (every ~1.7 hours) showing:
    • Current time (hours)
    • Total energy (kinetic + potential) [conserved quantity]
    • Total enstrophy (potential vorticity squared) [conserved quantity]
    • Maximum height deviation from mean
  • Summary: List of output fields that would be written (u, v, h, vorticity, divergence)

Runtime: Under 1 minute on modern hardware.

๐Ÿ”ฌ What to Observe

Energy Conservation: Total energy should remain nearly constant (variations < 0.1%). Large deviations indicate numerical instability.

Vortex Evolution: The initial vortex will evolve, possibly spawning Rossby waves that propagate westward (negative phase speed).

Enstrophy: Should also be approximately conserved in inviscid flow.

Performance Tips & Optimization

๐Ÿš€ Compiler Optimization Flags

# Level 3 optimization (aggressive)
-O3
# Optimize for your specific CPU architecture
-march=native
# Aggressive floating-point optimizations
-ffast-math
# Loop unrolling
-funroll-loops
# Enable vectorization reports (to see what's optimized)
-fopt-info-vec-optimized

These flags can provide 2-5ร— speedup compared to unoptimized code.

โšก Parallelization with OpenMP

Add OpenMP directives to parallelize loops across multiple CPU cores:

!$OMP PARALLEL DO PRIVATE(i,j)
do j = 1, ny
do i = 1, nx
! computations here
end do
end do
!$OMP END PARALLEL DO

Compile with: -fopenmp

๐ŸŽฏ Array Layout Optimization

Fortran stores arrays in column-major order. For optimal cache performance, access arrays with the first index varying fastest in innermost loops:

! Good (first index in innermost loop)
do k = 1, nz
do j = 1, ny
do i = 1, nx
T(i,j,k) = ...
! Bad (first index in outermost loop)
do i = 1, nx
do j = 1, ny
do k = 1, nz
T(i,j,k) = ...

๐Ÿ“Š Profiling Your Code

Use gprof to identify performance bottlenecks:

# Compile with profiling enabled
gfortran -o model model.f90 -O3 -pg
# Run the program (generates gmon.out)
./model
# Analyze profile
gprof model gmon.out > analysis.txt

๐ŸŒ Distributed Memory: MPI

For very large domains or operational-scale models, use MPI (Message Passing Interface) to distribute the computation across multiple compute nodes. This requires domain decomposition and explicit message passing between processes. Libraries like MPI-Fortran make this feasible.

Advanced Topics & Extensions

๐Ÿ“ Modifying the Models

Once you understand the basics, try these extensions:

  • Add output to netCDF files using netCDF-Fortran library
  • Implement different initial conditions (tropical cyclone, mountain wave)
  • Add topography to the shallow water model
  • Implement different numerical schemes (semi-Lagrangian, spectral methods)
  • Add tracer transport (passive scalar advection)

๐Ÿ”ฌ Testing Numerical Methods

These models are excellent testbeds for:

  • Comparing explicit vs. implicit time integration schemes
  • Testing conservation properties of different advection schemes
  • Evaluating numerical dispersion and diffusion
  • Studying CFL stability conditions

๐Ÿ“š Further Reading

  • Durran (2010): Numerical Methods for Fluid Dynamics โ€” comprehensive treatment
  • Lauritzen et al.: Numerical Techniques for Global Atmospheric Models
  • Kalnay (2003): Atmospheric Modeling, Data Assimilation and Predictability
  • WRF Documentation: Technical notes on operational NWP implementation

๐ŸŽ“ Learning Path

  1. Start with shallow water model (simpler, 2D, illustrates key concepts)
  2. Understand the primitive equations derivation (see Part II of course)
  3. Study the primitive equations model implementation
  4. Experiment with different parameters, initial conditions
  5. Implement extensions and additional physics
  6. Progress to full-scale community models (WRF, MPAS)

Additional Resources

Community NWP Models (Fortran-based):

  • WRF: Weather Research and Forecasting Model โ€” most widely used mesoscale model
  • MPAS: Model for Prediction Across Scales โ€” unstructured mesh, variable resolution
  • CAM: Community Atmosphere Model โ€” climate modeling
  • COSMO: Consortium for Small-scale Modeling

Online Tutorials:

  • Modern Fortran tutorial: fortran-lang.org
  • WRF online tutorial and documentation
  • NCAR CESM tutorial (climate modeling)

Computing Resources:

  • XSEDE (academic supercomputing access in the US)
  • Cloud computing (AWS, Google Cloud) with HPC instances
  • University cluster computing facilities