Skip to content
LumenaryAcademy
Professional 70 min

Tools of the trade, and an orbital simulator

Compilers, fpm, tests and the habits of professional Fortran teams, brought together in a small N-body simulation of planets and a comet.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

From one file to a project people trust

Every program in this course so far has been a single file that you compile with one command. Real Fortran rarely looks like that. A research code is dozens or hundreds of modules, built for several compilers, depending on libraries such as LAPACK or NetCDF, tested automatically whenever someone changes it, and run by people who did not write it, sometimes years later, to produce results that end up in papers and forecasts. What turns code into something others can trust is mostly not the language but the habits around it: a reproducible build, tests that check the numbers, documentation, and a record of exactly what produced each result.

For a long time Fortran's tooling lagged behind newer languages. That has changed a great deal since the Fortran-lang community formed around 2020, and this lesson surveys the tools professionals use now. Then it brings the whole course together in a project: a small gravitational simulation of a planet and a comet, built from modules, derived types, do concurrent and the numerical care of the earlier lessons, and checked against Kepler's laws.

ExplanationH

The modern Fortran toolbox

Compilers. Fortran has several good compilers, and serious projects test with more than one, because each catches different mistakes and implements different corners of the standard:

CompilerNotes
GFortranpart of GCC, free, on every platform; the reference for this course
LLVM Flangthe newer free compiler built on LLVM, installed as flang
Intel ifxfree to download; the successor of Intel's classic ifort, which Intel has discontinued
NVIDIA nvfortranaimed at GPUs, with CUDA Fortran, OpenACC and do concurrent offloading
HPE Cray, NAGon Cray supercomputers, and a commercial compiler known for very strict checking
LFortranan interactive compiler under development, usable in Jupyter notebooks

Build systems. For a single file, the compiler is enough. For a project, something must work out the order in which modules are compiled, since a module must be compiled before anything that uses it. The Fortran Package Manager, fpm, does this with no configuration and also fetches dependencies; the next section shows it. Large established codes mostly use CMake, which understands Fortran module dependencies natively, and some use Meson. Hand-written Makefiles still exist and are the most fragile option.

Libraries. The community's stdlib project adds what the intrinsic library lacks: sorting (stdlib_sorting), statistics (stdlib_stats), string utilities (stdlib_strings), simple file I/O such as loadtxt and savetxt (stdlib_io), linear algebra (stdlib_linalg) and more. Beyond it lies the ecosystem of decades: BLAS and LAPACK, FFTW for Fourier transforms, NetCDF and HDF5 for data, PETSc for large sparse systems, and many domain libraries. The package index on fortran-lang.org is a good place to look before writing something yourself.

Editors. The Modern Fortran extension for Visual Studio Code, and most other editors through the Language Server Protocol, use fortls, the Fortran language server, for completion, go-to-definition, hover documentation and on-the-fly diagnostics.

Style and static checks. Turn on compiler warnings (-Wall -Wextra, and -Wimplicit-interface to catch calls to procedures outside modules). fprettify formats code automatically, so reviews can be about substance rather than spacing, and Fortitude, a newer linter written in Rust, flags patterns such as missing implicit none, missing intents and obsolescent constructs.

Documentation. FORD generates browsable documentation from the source: it reads comments beginning with !> (before an item) or !! (after it), along with the module structure, call graphs and type hierarchies. The comments starting !> in this lesson's project are written for it.

Debugging and profiling. The debugging build from the first lesson (-g -fcheck=all -fbacktrace, plus -ffpe-trap=invalid,zero,overflow from the precision lesson) finds most errors. Beyond that, gdb works on Fortran programs, -fsanitize=address and Valgrind find memory errors in code with pointers or C interoperability, and gprof, perf or vendor profilers show where the time goes.

Continuous integration. Projects on GitHub and GitLab build and test every change automatically, typically on two or three compilers and operating systems. The community maintains a setup-fortran action that installs a chosen compiler on GitHub's machines.

ComputationC

fpm: a project in a few commands

fpm is available as a prebuilt executable and through package managers such as conda and pip; see fpm.fortran-lang.org for the options. A new project is one command:

bash
fpm new orbits
cd orbits
fpm run

fpm new creates a project with a conventional layout, and fpm finds everything by those conventions:

text
orbits/
  fpm.toml            the manifest: name, version, options, dependencies
  src/orbits.f90      library modules (any number of files, any directory depth)
  app/main.f90        programs: each file with a "program" becomes an executable
  test/check.f90      test programs, run by "fpm test"
  example/            optional example programs

The manifest is a short TOML file. One for this lesson's project might read:

toml
name = "orbits"
version = "0.1.0"
license = "MIT"
author = "Your Name"

[build]
auto-executables = true
auto-tests = true

[fortran]
implicit-typing = false      # as if every unit had implicit none (the default)
implicit-external = false    # require interfaces for external procedures (the default)
source-form = "free"

[dependencies]
stdlib = "*"                 # a "metapackage": fpm knows how to fetch and build it

[dev-dependencies]
test-drive = { git = "https://github.com/fortran-lang/test-drive" }

Dependencies are other fpm projects, named by a git repository and pinned to a tag, branch or commit, or, for a few widely used packages (stdlib, OpenMP, MPI, HDF5, NetCDF, BLAS and MINPACK), "metapackages" written as name = "*". [dev-dependencies] are needed only by the tests. In a real project, pin every git dependency with tag = "..." or rev = "...", so that a change upstream cannot silently change your build.

The everyday commands:

bash
fpm build                       # compile everything, in dependency order, with debug options
fpm run -- 500                  # build and run the program; arguments after -- are passed to it
fpm test                        # build and run every program in test/; fails if any test fails
fpm run --profile release       # optimised build
fpm build --flag "-fopenmp"     # extra compiler flags
fpm build --compiler flang      # another compiler

fpm decides the compilation order by reading the use statements, and it builds the debug profile by default, with run-time checks and warnings on. For an existing code that uses CMake, there is no need to switch: many projects ship both a CMakeLists.txt and an fpm.toml, so that they can be used as fpm dependencies too.

Worked examplesH

Programs meant for other people

A program that only its author runs can hard-wire its settings. A program others run needs a little more: arguments with sensible defaults, a clear message and a nonzero exit status when something is wrong (scripts, job schedulers and fpm test all look at the exit status), and output that records how it was produced. The intrinsic module iso_fortran_env can tell a program which compiler built it:

fortran
! A command-line program that records how it was built and run
program provenance
  use, intrinsic :: iso_fortran_env, only: compiler_version, compiler_options, error_unit
  implicit none
  integer :: steps, length, status
  character(len=:), allocatable :: arg

  ! An optional first argument sets the number of steps; without one, use a default
  steps = 1000
  if (command_argument_count() >= 1) then
     call get_command_argument(1, length=length)
     allocate(character(len=length) :: arg)
     call get_command_argument(1, arg)
     read (arg, *, iostat=status) steps
     if (status /= 0 .or. steps < 1) then
        write (error_unit, '(a)') 'usage: provenance [steps], where steps is a positive integer'
        error stop 2
     end if
  end if

  ! Provenance: which compiler and which options produced this executable
  print '(a)', '# compiler: ' // compiler_version()
  print '(a)', '# options:  ' // compiler_options()
  print '(a, i0)', '# steps:    ', steps
end program provenance

Run with no arguments, it printed:

text
# compiler: GCC version 11.4.0
# options:  -mtune=generic -march=x86-64 -Wall -std=f2018 -fpre-include=/usr/include/finclude/math-vector-fortran.h
# steps:    1000
  • command_argument_count and get_command_argument (Fortran 2003) read the command line. Asking first for the argument's length and then allocating a deferred-length string avoids guessing a buffer size.
  • Validation by internal read. read (arg, *, iostat=status) steps converts the text to an integer and reports failure instead of crashing. Run as ./provenance ten, the program printed the usage message on the error stream and stopped with exit status 2; run as ./provenance 250, its last line was # steps: 250.
  • error_unit is the standard error stream, where diagnostics belong, so that they do not mix with results that may be redirected to a file.
  • compiler_version() and compiler_options() (Fortran 2008) return strings describing the build. The options line shows what GFortran was really given, including -fpre-include, which this Linux distribution's GFortran adds so that loops can call vectorised versions of maths functions. Writing such a header at the top of every output file costs one line and answers, months later, the question "which build produced these numbers?". The # makes the header a comment for most plotting and analysis tools.
Worked examplesH

Testing numerical code

Testing numerical code is different from testing, say, a string function, because the right answer is rarely known exactly and floating-point results are never compared with ==. Experienced developers use three kinds of test: comparison with known solutions within a tolerance; convergence tests, which check that the error shrinks at the rate the theory predicts as the step size falls; and invariants, quantities such as energy or mass that the physics conserves. Here are all three for the leapfrog method, which the project below uses, applied to the oscillator x′′=−xx'' = -x, whose exact solution from x=1x = 1, v=0v = 0 is x=cos⁡tx = \cos t, v=−sin⁡tv = -\sin t:

fortran
! Testing numerical code: a known solution, tolerances, and the order of convergence
module oscillator
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none
  private
  public :: dp, leapfrog, euler

contains

  !> Solve x'' = -x with x(0) = 1, x'(0) = 0 in n steps up to t_end by the leapfrog method;
  !> return the final state [x, v].
  pure function leapfrog(t_end, n) result(state)
    real(dp), intent(in) :: t_end
    integer, intent(in) :: n
    real(dp) :: state(2), x, v, dt
    integer :: k
    dt = t_end / n
    x = 1.0_dp
    v = 0.0_dp
    do k = 1, n
       v = v - 0.5_dp * dt * x
       x = x + dt * v
       v = v - 0.5_dp * dt * x
    end do
    state = [x, v]
  end function leapfrog

  !> The same problem by the explicit Euler method.
  pure function euler(t_end, n) result(state)
    real(dp), intent(in) :: t_end
    integer, intent(in) :: n
    real(dp) :: state(2), x, v, dt, x_old
    integer :: k
    dt = t_end / n
    x = 1.0_dp
    v = 0.0_dp
    do k = 1, n
       x_old = x
       x = x + dt * v
       v = v - dt * x_old
    end do
    state = [x, v]
  end function euler

end module oscillator


module checks
  implicit none
  private
  public :: check, failures
  integer :: failures = 0

contains

  subroutine check(name, passed, detail)
    character(len=*), intent(in) :: name, detail
    logical, intent(in) :: passed
    if (passed) then
       print '(a, a, " (", a, ")")', 'PASS  ', name, detail
    else
       print '(a, a, " (", a, ")")', 'FAIL  ', name, detail
       failures = failures + 1
    end if
  end subroutine check

end module checks


program test_oscillator
  use oscillator, only: dp, leapfrog, euler
  use checks, only: check, failures
  implicit none
  real(dp), parameter :: t_end = 10.0_dp, exact(2) = [cos(t_end), -sin(t_end)]
  real(dp) :: err1, err2, order, energy
  character(len=40) :: detail

  ! 1. Compare with the exact solution, x = cos(t), v = -sin(t), using a tolerance, never ==
  err1 = norm2(leapfrog(t_end, 1000) - exact)
  write (detail, '(a, es8.1)') 'error ', err1
  call check('leapfrog agrees with the exact solution', err1 < 1.0e-4_dp, trim(detail))

  ! 2. Halving the step should divide a second-order method's error by about 4
  err2 = norm2(leapfrog(t_end, 2000) - exact)
  order = log(err1 / err2) / log(2.0_dp)
  write (detail, '(a, f4.2)') 'observed order ', order
  call check('leapfrog converges at second order', abs(order - 2.0_dp) < 0.1_dp, trim(detail))

  ! 3. ... and a first-order method's error by about 2
  order = log(norm2(euler(t_end, 100000) - exact) / norm2(euler(t_end, 200000) - exact)) / log(2.0_dp)
  write (detail, '(a, f4.2)') 'observed order ', order
  call check('Euler converges at first order', abs(order - 1.0_dp) < 0.1_dp, trim(detail))

  ! 4. An invariant: after 1000 periods the energy (x**2 + v**2) / 2 is still close to 1/2
  energy = 0.5_dp * sum(leapfrog(2000.0_dp * acos(-1.0_dp), 200000)**2)
  write (detail, '(a, es8.1)') 'energy change ', abs(energy - 0.5_dp)
  call check('leapfrog conserves energy over 1000 periods', abs(energy - 0.5_dp) < 1.0e-3_dp, trim(detail))

  if (failures > 0) error stop 'some tests failed'
  print '(a)', 'all tests passed'
end program test_oscillator

It prints:

text
PASS  leapfrog agrees with the exact solution (error  3.6E-05)
PASS  leapfrog converges at second order (observed order 2.00)
PASS  Euler converges at first order (observed order 1.00)
PASS  leapfrog conserves energy over 1000 periods (energy change  8.1E-06)
all tests passed

The observed order is the most powerful of these tests. If a method's error is proportional to Δtp\Delta t^p, halving Δt\Delta t divides the error by 2p2^p, so p=log⁡2(e1/e2)p = \log_2(e_1 / e_2). A sign error or a misplaced half-step usually leaves a method that still gives plausible numbers but converges at the wrong order, which this test catches at once. The tolerances are chosen from the theory, with some margin: an order within 0.1 of 2, an error below 10−410^{-4}.

A story about test 4. Our first version checked something else: that after 1000 whole periods, xx was back at 1. It failed:

text
FAIL  leapfrog returns to x = 1 after 1000 periods (x - 1 = -3.3E-02)
ERROR STOP some tests failed

and the program stopped with exit status 1. The method was fine; the test was wrong. Leapfrog keeps the energy of an oscillation almost exactly, but its frequency is very slightly off (by a relative amount of about Δt2/24\Delta t^2 / 24), and over 1000 periods that small phase error had grown to about a quarter of a radian. Energy is the invariant leapfrog conserves; phase is not. Deciding what a numerical method should and should not get right is half the work of testing it.

error stop matters here too: it ends the program with a nonzero exit status, which is how fpm test and continuous-integration systems know the tests failed. With the test-drive framework, the same checks are written as named tests that a runner collects and reports, and fpm test runs them:

fortran
subroutine test_second_order(error)
  type(error_type), allocatable, intent(out) :: error
  real(dp) :: order
  order = log(norm2(leapfrog(t_end, 1000) - exact) / norm2(leapfrog(t_end, 2000) - exact)) / log(2.0_dp)
  call check(error, abs(order - 2.0_dp) < 0.1_dp, 'leapfrog should be second order')
  if (allocated(error)) return
end subroutine test_second_order
Worked examplesH

Project: an orbital simulator

Now the project. The goal is a small program that simulates bodies moving under their mutual gravity, checked against what is known exactly: a circular orbit should stay circular, energy should be conserved, and Kepler's third law gives the period of any orbit around the Sun.

The physics. Each body ii, with mass mim_i at position xi\mathbf{x}_i, is accelerated by every other body:

ai=∑j≠iGmj xj−xi∥xj−xi∥3.\mathbf{a}_i = \sum_{j \ne i} G m_j \, \frac{\mathbf{x}_j - \mathbf{x}_i}{\lVert \mathbf{x}_j - \mathbf{x}_i \rVert^3}.

Choosing units well removes most constants: with distances in astronomical units (AU, the Earth's mean distance from the Sun), time in years and masses in solar masses, Kepler's third law for the Earth fixes GM⊙=4π2G M_\odot = 4\pi^2, and the period in years of any orbit around the Sun with semi-major axis aa AU is simply T=a3/2T = a^{3/2}.

The method. The program advances time in steps of Δt\Delta t with the leapfrog method (also called velocity Verlet): half a step of velocity change, a full step of motion, then the second half of the velocity change at the new positions. It is only second order, but it is symplectic: it exactly conserves a quantity very close to the true energy, so its energy error oscillates instead of growing. For orbits followed for many revolutions, that matters more than a high order. The explicit Euler method, kept for comparison, has no such property.

The design. Three modules and a program, which in an fpm project would be the files src/orbits_constants.f90, src/orbits_nbody.f90 and app/main.f90: a constants module fixing the precision and the units; a module with a body_system derived type (a structure of arrays, as the derived-types lesson discussed, since the inner loops touch all positions at once) with type-bound procedures for the energy and the two steppers; and a main program running the experiments. The force loop is a do concurrent over the bodies, from the previous lesson.

fortran
! orbits: a small gravitational N-body simulator in one file.
! In an fpm project, each module would be a file under src/ and the program would be app/main.f90.

module orbits_constants
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none
  private
  public :: dp, pi, gm_sun

  real(dp), parameter :: pi = acos(-1.0_dp)
  !> Units: astronomical units (AU), years and solar masses, in which G * M_sun = 4 pi**2.
  real(dp), parameter :: gm_sun = 4.0_dp * pi**2
end module orbits_constants


module orbits_nbody
  use orbits_constants, only: dp
  implicit none
  private
  public :: body_system, new_system

  !> Bodies moving under their mutual gravity, in a plane, stored as a structure of arrays.
  type :: body_system
     integer :: n = 0
     real(dp), allocatable :: gm(:)        ! G times the mass of each body (AU**3 / year**2)
     real(dp), allocatable :: x(:, :)      ! x(:, i) is the position of body i (AU)
     real(dp), allocatable :: v(:, :)      ! v(:, i) is its velocity (AU / year)
     real(dp) :: time = 0.0_dp             ! years
   contains
     procedure :: energy
     procedure :: leapfrog_step
     procedure :: euler_step
  end type body_system

contains

  !> Build a system and move it to the centre-of-mass frame, so that it does not drift.
  function new_system(gm, x, v) result(s)
    real(dp), intent(in) :: gm(:), x(:, :), v(:, :)
    type(body_system) :: s
    integer :: i
    s%n = size(gm)
    allocate(s%gm, source=gm)
    allocate(s%x, source=x)
    allocate(s%v, source=v)
    do i = 1, s%n
       s%x(:, i) = s%x(:, i) - matmul(x, gm) / sum(gm)
       s%v(:, i) = s%v(:, i) - matmul(v, gm) / sum(gm)
    end do
  end function new_system

  !> Gravitational acceleration of every body, summed over all the others.
  pure function accelerations(s) result(a)
    type(body_system), intent(in) :: s
    real(dp) :: a(size(s%x, 1), s%n)
    integer :: i
    do concurrent (i = 1:s%n)
       block
         integer :: j
         real(dp) :: d(size(s%x, 1))
         a(:, i) = 0.0_dp
         do j = 1, s%n
            if (j == i) cycle
            d = s%x(:, j) - s%x(:, i)
            a(:, i) = a(:, i) + s%gm(j) * d / norm2(d)**3
         end do
       end block
    end do
  end function accelerations

  !> Total energy divided by G: kinetic minus the potential of every pair.
  pure function energy(s) result(e)
    class(body_system), intent(in) :: s
    real(dp) :: e
    integer :: i, j
    e = 0.5_dp * sum(s%gm * sum(s%v**2, dim=1))
    do i = 1, s%n - 1
       do j = i + 1, s%n
          e = e - s%gm(i) * s%gm(j) / norm2(s%x(:, i) - s%x(:, j))
       end do
    end do
  end function energy

  !> One step of the leapfrog (velocity Verlet) method: half kick, drift, half kick.
  subroutine leapfrog_step(s, dt)
    class(body_system), intent(inout) :: s
    real(dp), intent(in) :: dt
    s%v = s%v + 0.5_dp * dt * accelerations(s)
    s%x = s%x + dt * s%v
    s%v = s%v + 0.5_dp * dt * accelerations(s)
    s%time = s%time + dt
  end subroutine leapfrog_step

  !> One step of the explicit Euler method, for comparison.
  subroutine euler_step(s, dt)
    class(body_system), intent(inout) :: s
    real(dp), intent(in) :: dt
    real(dp) :: a(size(s%x, 1), s%n)
    a = accelerations(s)
    s%x = s%x + dt * s%v
    s%v = s%v + dt * a
    s%time = s%time + dt
  end subroutine euler_step

end module orbits_nbody


program orbits
  use orbits_constants, only: dp, pi, gm_sun
  use orbits_nbody, only: body_system, new_system
  implicit none
  real(dp), parameter :: gm_earth = 3.003e-6_dp * gm_sun      ! the Earth's mass is 3.003e-6 solar masses
  type(body_system) :: euler, leapfrog, comet
  real(dp) :: dt, e0, a, ecc, rmax, rmin, radial, last_radial, worst, t_peri(2)
  integer :: k, passes

  ! 1. The Earth around the Sun for one year, one step per day, with two methods
  dt = 1.0_dp / 365.0_dp
  euler = new_system([gm_sun, gm_earth], reshape([0.0_dp, 0.0_dp, 1.0_dp, 0.0_dp], [2, 2]), &
                     reshape([0.0_dp, 0.0_dp, 0.0_dp, 2.0_dp * pi], [2, 2]))
  leapfrog = euler
  e0 = euler%energy()
  do k = 1, 365
     call euler%euler_step(dt)
     call leapfrog%leapfrog_step(dt)
  end do
  print '(a)', 'Earth after one year, 365 steps of one day:'
  print '(a, f8.5, a, es9.2)', '  Euler:    distance from the Sun ', distance(euler), ' AU, energy error ', &
        abs(euler%energy() / e0 - 1.0_dp)
  print '(a, f8.5, a, es9.2)', '  leapfrog: distance from the Sun ', distance(leapfrog), ' AU, energy error ', &
        abs(leapfrog%energy() / e0 - 1.0_dp)

  ! 2. A comet on a Halley-like orbit, started at aphelion
  a = 17.8_dp                                   ! semi-major axis, AU
  ecc = 0.967_dp                                ! eccentricity
  rmax = a * (1.0_dp + ecc)
  comet = new_system([gm_sun, 1.0e-16_dp * gm_sun], reshape([0.0_dp, 0.0_dp, rmax, 0.0_dp], [2, 2]), &
                     reshape([0.0_dp, 0.0_dp, 0.0_dp, sqrt(gm_sun * (1.0_dp - ecc) / rmax)], [2, 2]))
  e0 = comet%energy()
  dt = 0.001_dp
  passes = 0
  rmin = huge(1.0_dp)
  worst = 0.0_dp
  last_radial = 0.0_dp
  do k = 1, 150000                              ! 150 years, just under two orbits
     call comet%leapfrog_step(dt)
     rmin = min(rmin, distance(comet))
     worst = max(worst, abs(comet%energy() / e0 - 1.0_dp))
     radial = dot_product(comet%x(:, 2) - comet%x(:, 1), comet%v(:, 2) - comet%v(:, 1))
     if (last_radial < 0.0_dp .and. radial >= 0.0_dp) then   ! falling in turns to moving out
        passes = passes + 1
        t_peri(passes) = comet%time
     end if
     last_radial = radial
  end do
  print '(a)', 'Comet with a = 17.8 AU and e = 0.967, 150 years in steps of 0.001 years:'
  print '(a, f7.4, a, f7.4, a)', '  closest approach ', rmin, ' AU (predicted ', a * (1.0_dp - ecc), ' AU)'
  print '(a, 2f9.3)', '  perihelion passages in years ', t_peri(1:passes)
  print '(a, f7.3, a, f7.3, a)', '  period ', t_peri(2) - t_peri(1), ' years (Kepler''s third law: ', a**1.5_dp, ' years)'
  print '(a, es9.2, a, es9.2)', '  energy error: largest ', worst, ', at the end ', abs(comet%energy() / e0 - 1.0_dp)

contains

  pure function distance(s) result(d)
    type(body_system), intent(in) :: s
    real(dp) :: d
    d = norm2(s%x(:, 2) - s%x(:, 1))
  end function distance

end program orbits

It prints:

text
Earth after one year, 365 steps of one day:
  Euler:    distance from the Sun  1.20578 AU, energy error  1.53E-01
  leapfrog: distance from the Sun  1.00000 AU, energy error  3.77E-15
Comet with a = 17.8 AU and e = 0.967, 150 years in steps of 0.001 years:
  closest approach  0.5874 AU (predicted  0.5874 AU)
  perihelion passages in years    37.550  112.648
  period  75.098 years (Kepler's third law:  75.098 years)
  energy error: largest  1.44E-03, at the end  2.48E-13

Reading the results

Euler fails in a characteristic way. After one year of daily steps, the Euler Earth is 1.206 AU from the Sun and its energy is 15 % off. Each Euler step moves the planet along the tangent of its orbit, which always carries it slightly outwards, so it gains energy every step and spirals away. Smaller steps would slow the drift, but never stop it. The leapfrog Earth, with exactly the same steps, is still at 1.00000 AU. (As written, leapfrog computes the forces twice per step; a tuned version reuses the second evaluation as the next step's first, so it costs no more than Euler.)

The comet checks the code against Kepler. It starts at aphelion, a(1+e)=35.0a(1 + e) = 35.0 AU from the Sun, with the speed the vis-viva equation gives there. The simulation found the closest approach at 0.5874 AU, which is a(1−e)a(1 - e), and two perihelion passages 75.098 years apart, exactly Kepler's a3/2a^{3/2} to the printed precision. (Halley's comet has a≈17.8a \approx 17.8 AU and e≈0.967e \approx 0.967; its real period varies between about 74 and 79 years, because Jupiter and Saturn tug on it, which a two-body model leaves out.) Perihelion passages are detected without any special mathematics: the radial velocity, (x2−x1)⋅(v2−v1)(\mathbf{x}_2 - \mathbf{x}_1) \cdot (\mathbf{v}_2 - \mathbf{v}_1), changes sign from negative (falling in) to positive (moving out).

The energy error shows what symplectic means. At its worst, during the fast swing past the Sun, the energy was off by 0.14 %, because a fixed step of 0.001 years is coarse when the comet moves at its fastest. Yet when the comet returned to the far end of its orbit, the error had fallen back to 2.5×10−132.5 \times 10^{-13}. Leapfrog's error oscillates around the orbit instead of accumulating. A production code would also shrink the step near perihelion (adaptive time-stepping, done carefully so as not to spoil the symplectic property), which is how professional orbit integrators follow comets for millions of years.

The code shows the course. Kinds come from one module; every procedure lives in a module with private by default; new_system uses sourced allocation and whole-array expressions to move to the centre-of-mass frame (without it, the Sun's recoil would make the whole system drift slowly across the grid); the force computation is a pure function with a do concurrent loop whose iterations are independent; norm2 and matmul replace hand-written loops; and every literal carries _dp.

To grow it into a real tool, in rough order: move each module into its own file in an fpm project and turn the checks above (Kepler's period, the energy invariant, the convergence order) into tests in test/; read the bodies and settings from a namelist file, as in the precision lesson; write the trajectory to a CSV or NetCDF file with a provenance header and plot it; add Jupiter and Saturn and watch the comet's period change; and, for thousands of bodies, profile, then parallelise the force loop with OpenMP or offload it to a GPU.

Common misconceptionsH

Misconceptions

Misconception

"Agreement with one expected number means the code is right." A wrong method can match at one step size by luck. Test how the error changes: a convergence test catches mistakes that a single comparison misses.

Misconception

"A higher-order method is always better." For long orbital integrations, a second-order symplectic method such as leapfrog often beats a classical fourth-order Runge–Kutta method of similar cost, because the Runge–Kutta energy error, though tiny per step, drifts steadily. The right method depends on what must be conserved and for how long.

Misconception

"fpm and CMake are rivals; a project must choose one." They serve overlapping purposes, and many libraries ship both files, so they can be built either way and used as fpm dependencies.

Further reading

Where to go next

You now know the language that most of the world's large scientific codes are written in, from its first loop to its parallel features and its border with C and Python. Some directions from here:

  • Practise on real problems. Port a small numerical method you know (a root finder, an ODE solver, a heat-equation solver) to a tested fpm project, then profile and parallelise it.
  • Read real code. Open-source Fortran projects range from compact libraries in fpm's style (the stdlib, test-drive and the packages listed on fortran-lang.org) to large climate, ocean and chemistry models whose source is public. Reading how they organise modules and tests is an education in itself.
  • Learn the libraries of your field: LAPACK for linear algebra, FFTW, NetCDF or HDF5 for data, PETSc for large solvers, MPI for clusters.
  • Read a book. Modern Fortran Explained by Metcalf, Reid and Cohen is the standard reference, revised with each new standard; Milan Curcic's Modern Fortran teaches through a project, including parallel programming.
  • Join the community. The Fortran Discourse forum is friendly to newcomers, and compiler developers and members of the standards committee answer questions there. Contributions to stdlib, fpm or the compilers are welcome.
Optional Christian reflection · Patient work that others build on

A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.

The first FORTRAN compiler took a small team three years, and its authors cared above all that people would trust its output. Much of the Fortran still running today was written by people who never met its present users: a solver written decades ago inside a modern forecast, a library maintained by volunteers for a generation. There is something worth honouring in work done carefully for people you will never see. Writing a test that catches your own mistake, or a comment that will save a stranger a week, is a small act of service, whatever one believes about why such service matters.

Exercises

Exercises

1. Tools of the trade, and an orbital simulator

Warm-upHuman

Which fpm command builds the project and runs every test program in its test/ directory?

2. Tools of the trade, and an orbital simulator

Warm-upHuman

In an fpm project, where should the module orbits_nbody, used by both the main program and the tests, be placed?

Choose one

3. Tools of the trade, and an orbital simulator

CoreComputational

In the project's units (AU, years, solar masses), Kepler's third law says that a body orbiting the Sun with semi-major axis aa AU has period T=a3/2T = a^{3/2} years. What is the period, in years, of an asteroid with a=4a = 4 AU?

4. Tools of the trade, and an orbital simulator

CoreHuman

A convergence test finds that halving the time step divides a method's error by 8. What order is the method?

5. Tools of the trade, and an orbital simulator

CoreComputational

The lesson's provenance program is run as ./provenance 250. What is the last line it prints?

6. Tools of the trade, and an orbital simulator

CoreHuman

With 365 daily steps, the Euler Earth ended the year 1.206 AU from the Sun with its energy 15 % off, while the leapfrog Earth stayed at 1.00000 AU. Why does Euler fail this way?

Choose one

7. Tools of the trade, and an orbital simulator

StretchHuman

The first version of test 4 checked that leapfrog's xx returned to 1 after 1000 periods of x′′=−xx'' = -x, and it failed with x−1=−0.033x - 1 = -0.033, although the energy test passed with a change of 8×10−68 \times 10^{-6}. What does this show?

Choose one

8. Tools of the trade, and an orbital simulator

CoreHuman

Why does the test program end with if (failures > 0) error stop 'some tests failed' rather than just printing how many tests failed?

Choose one

Further reading and resources

  • Fortran Package Manager (fpm)The tutorial and the specification of fpm.toml, including dependencies and metapackages.
  • Fortran stdlibThe community standard library, with modules for sorting, statistics, strings, I/O and linear algebra.
  • test-driveA small, dependency-free unit-testing framework for Fortran that works with fpm, CMake and Meson.
  • FORD, the Fortran documenterGenerates browsable documentation from source code and its comments.
  • fortlsThe Fortran language server behind completion, hover and diagnostics in many editors.
  • Modern Fortran Explained · Michael Metcalf, John Reid and Malcolm CohenThe standard reference book on the language, revised with each new standard by authors who have worked on the standard itself.
  • Modern Fortran: Building efficient parallel applications · Milan Curcic · 2020A project-driven book on modern Fortran, including parallel programming and working with fpm-style projects.