Scientific computing · C99 / Python

PhaseFlow

I rebuilt three of my university transport assignments into one C simulation toolkit: a travelling pulse, a reacting river and a density moving through position–velocity space, each checked against exact solutions.

Kinetic C result at t = 0.4, F = 0.5 and C = 0.18: density f across position x and velocity v, on a fixed linear colour scale from 0 to 1.
Kinetic model, t = 0.4. Density entering from both edges, pushed by a force (F = 0.5) and spread in velocity (C = 0.18). Play the saved frames ↓
PDE models in one C99 executable
3
validation studies passing
18 / 18
faster Kinetic solve after reusing LU factors
18.9%
local explorer for comparing new runs
A/B

Three numerical experiments

Each experiment asks one question and answers it by changing a single setting. Every figure is output from the C solvers; all quantities are nondimensional.

01 · Transport · periodic pulse

How much spreading comes from the method?

Even with no physical diffusion, the pulse widens: first-order upwinding adds numerical diffusion of its own. A finer grid cuts that spreading by about 7×, and adding real diffusion raises it by almost exactly the amount added.

Transport comparison at t = 0.2: the initial Gaussian pulse and the pulse after advection on a 32-node grid with D = 0, a 192-node grid with D = 0 and a 192-node grid with D = 0.008, beside a bar chart of the measured spreading for each case.
Left: the pulse after travelling to t = 0.2 on each grid. Right: the measured spreading, with the added physical diffusion D = 0.008 dashed. Full size ↗
Spreading with D = 0, 32 → 192 nodes
0.0152 → 0.00220
Spreading on 192 nodes with D = 0.008
0.0102

∂tu + a ∂xu = D ∂²xu

Setup, measure and limits

The spreading measure is [Var(t) − Var(0)] / (2t): growth in the pulse’s squared width per twice the elapsed time, using mass-weighted distances around the expected centre, wrapped across the periodic boundary. The runs use 32 and 192 nodes, a = 1, Δt = 0.0008 and t = 0.2. Values are rounded to three significant figures; the manifest keeps them unrounded.

This smooth, short-time periodic pulse does not validate discontinuities or other boundaries. A small mass-balance residual alone does not establish pulse-shape accuracy.

02 · River · steady solution

Change the reaction, keep the source.

A localized source feeds pollutant P, which converts into product Q while both are carried downstream. Raising the conversion rate from k = 0.2 to 1.2 shifts concentration from P to Q, yet the total P + Q profile is unchanged to within 1.8 × 10−14.

River steady concentrations along the river at conversion rates k = 0.2 and k = 1.2: parent P, product Q and the unchanged total P + Q.
Steady concentrations along the river for the slower (left) and faster (right) conversion rate, from a direct banded LAPACK solve. Full size ↗
Total parent ∫P dx, k = 0.2 → 1.2
0.121 → 0.0798
Total product ∫Q dx, same change
0.0136 → 0.0547

The total stays fixed because the reaction only transfers concentration between the two species.

Setup, boundaries and limits

The runs use 121 nodes, a = D = 0.5 and a Gaussian source centred at x = 0.25. Each species has zero total flux upstream and zero concentration downstream. Values are rounded to three significant figures; the manifest keeps them unrounded.

The downstream concentration is imposed. This open steady system is a mathematical experiment, with no claim to environmental calibration or freely draining outflow.

03 · Kinetic · position and velocity

Diffusion changes the whole distribution.

Density enters from opposite edges of a position–velocity domain. A force shifts its velocity and diffusion spreads it along the velocity axis, filling in the gap at v = 0. The lower panels collapse each field onto velocity alone.

Kinetic beam injection at t = 0.4 for no force with C = 0.02, F = 0.5 with C = 0.02 and F = 0.5 with C = 0.18: phase-space density heatmaps on a common scale above the velocity marginal g(v) for each case.
Phase-space density at t = 0.4 on a common colour scale (top) and the velocity marginal g(v) = ∫ f dx (bottom), for three force and diffusion settings. Full size ↗
g(0) at F = 0.5, C = 0.02 → 0.18
0.0549 → 0.0804
Total phase-space integral, same change
0.233 → 0.191

∂tf + v ∂xf + F ∂vf = C ∂²vf

More diffusion raises g(0), but more density also escapes at the fixed velocity endpoints, so the total falls and the normalized velocity spread narrows in this example.

Step through the saved states

Choose a setting and play the four states the C solver wrote between t = 0 and t = 0.4.

Setup and limits

An 81 × 81 grid over x ∈ [0, 1] and v ∈ [−1, 1], with an initially empty interior. Incoming beams have density exp(−v²); spatial outflow copies its neighbour and f = 0 at v = ±1. The two diffusion cases share a timestep; changing force also changes the CFL-selected timestep. Values are rounded to three significant figures; the manifest keeps them unrounded.

This is an open, truncated domain. These fields do not establish convergence of the full split scheme, particle trajectories or thermal relaxation.

Kinetic C result: Force F = 0.5 · C = 0.18; saved state at t = 0.4000. Position x is horizontal, velocity v is vertical; colour gives density f on the fixed linear scale 0–1.
Force F = 0.5 · C = 0.18 · saved state t = 0.4000 · frame 4 of 4 · fixed linear density scale 0–1

04 · Run new experiments

A local explorer for new runs.

The Streamlit explorer launches the C executable from the browser on my own machine, so new settings give new results rather than saved ones.

  • Run. Pick a model and one of eight presets, adjust its settings and run the solver.
  • Compare. Run A against B and inspect both fields, and their difference, at the same saved times.
  • Replay. Step through saved states on fixed axes, with diagnostics for each frame.
  • Revisit. Reopen, search and filter earlier runs from local history.

Bounded for interactive use: 30 seconds per solve, 80 saved frames and Kinetic grids up to 129 × 129.

The PhaseFlow Streamlit explorer: experiment setup controls on the left; on the right a completed Kinetic run with playback controls, a phase-space heatmap with position and velocity marginals, and diagnostics.
The explorer after a symmetric beam-injection Kinetic run (C = 0.12, t = 0.2).

05 · Engineering and validation

How I know it works.

Around the original solvers I added a shared executable, scalar Transport, Python reference tests, saved-run diagnostics, comparison tools and the explorer, then used a benchmark to guide one targeted optimisation.

  1. C

    Computes

    Explicit upwind transport, finite-difference diffusion and banded LAPACKE solves write fields and diagnostics.

  2. Py

    Checks

    Independent references and grid refinement measure error. Input, build and CSV hashes tie each figure to its recorded run.

  3. UI

    Displays

    This page shows saved C output; the local explorer runs the solver for new settings.

Checked against exact solutions

The recorded validation suite passes all 18 studies. Three of them are shown here: each solver is run on a problem with a known answer at three resolutions, and the error should shrink at a predictable rate as the grid is refined.

Periodic Transport advection

A smooth cosine wave travelling around a periodic domain, compared with its exact translation.

Finest-grid error (absolute weighted L2)
4.29e-3
Finest grid
128 nodes

Spatial L2 orders: 0.954, 0.977

Orders near one, as expected for first-order upwinding.

Reference, refinement and precision

The cosine travels at a = 1 on the periodic interval [0, 1], with D = k = 0, to t = 0.2. The reference is its exact translation, not the Gaussian pulse above.

32 → 64 → 128 unique nodes. The timestep decreases with the square of the spacing; its measured temporal contribution stays below 2% of the continuum L2 error on every grid.

Periodic rectangle weights, w = Δx = 1/N.

Finest Δt = 3.05e-6. Recorded reference: exp(-kT)[1+0.2 exp(-4 pi^2 D T) cos(2 pi (x-aT))]

Level 1 · 32 nodes · Δt = 0.000048828125
Absolute L2: 0.016375582753368097
Level 2 · 64 nodes · Δt = 0.00001220703125
Absolute L2: 0.008451522553761241
Level 3 · 128 nodes · Δt = 0.0000030517578125
Absolute L2: 0.0042932868806031645

Unrounded orders: 0.954263074879278, 0.9771286904082512.

This smooth periodic mode does not cover discontinuities or other boundaries.

Steady River reaction–diffusion

A direct steady solve compared with an analytical cosh-shaped solution.

Finest-grid error (absolute weighted L2)
3.39e-3
Finest grid
81 nodes

Spatial L2 orders: 1.010, 1.005

Orders near one: the first-order upstream boundary condition sets the accuracy.

Reference, refinement and precision

D = 1, k = 0.5, no advection and no source. The analytical reference is P = 2 cosh(√0.5 x)/cosh(√0.5), Q = 3 − P, on [0, 1], with zero upstream derivatives and downstream P = 2, Q = 1.

21 → 41 → 81 endpoint-inclusive nodes. There is no timestep or initial condition: the recorded Δt = 0 denotes a direct steady solve, so no temporal order is inferred.

Endpoint trapezoidal weights, with half weights at the endpoints. P and Q squared errors are summed without dividing by the number of species.

Direct steady solve · no timestep. Recorded reference: P=2 cosh(sqrt(0.5)x)/cosh(sqrt(0.5)); Q=3-P. ODE and boundaries checked before use.

Level 1 · 21 nodes · Δt = 0
Absolute L2: 0.01369393943326072
Level 2 · 41 nodes · Δt = 0
Absolute L2: 0.006797819713917094
Level 3 · 81 nodes · Δt = 0
Absolute L2: 0.0033870835780022363

Unrounded orders: 1.0103935311308112, 1.0050285139350972.

This is a different boundary-value problem from the River experiment above.

Isolated Kinetic velocity diffusion

A cosine mode decaying under velocity diffusion alone, compared with its exact decay.

Finest-grid error (absolute weighted L2)
2.03e-5
Finest grid
3 × 65 nodes

Spatial L2 orders: 1.997, 1.995

Orders near two for the production velocity-diffusion operator.

Reference, refinement and precision

The mode cos(πv/4) decays as exp[−0.3(π/4)²t] on v ∈ [−2, 2], with zero velocity endpoints, to t = 0.2. Position is inactive, so this tests the diffusion operator in isolation.

3 × 17 → 3 × 33 → 3 × 65 nodes in x × v. Velocity intervals double while Δt = 0.00001 stays fixed. The exact discrete eigenmode bounds the temporal contribution below 2% of continuum L2 error on every grid.

Tensor-product trapezoidal x/v weights; the inactive position interval is [0, 4].

Finest Δt = 1.00e-5. Recorded reference: cos(pi v/4) exp(-C(pi/4)^2 T)

Level 1 · 3 × 17 nodes · Δt = 0.00001
Absolute L2: 0.00032379712239257916
Level 2 · 3 × 33 nodes · Δt = 0.00001
Absolute L2: 0.00008109371148857252
Level 3 · 3 × 65 nodes · Δt = 0.00001
Absolute L2: 0.000020348088909296584

Unrounded orders: 1.9974282160324628, 1.994696740157776.

This does not validate force/diffusion splitting, injection-front accuracy or the full boundary treatment of the experiment above.

How to read these numbers

Each error is an absolute weighted L2 error: the square root of the weighted sum of squared differences from the reference, across the whole domain. It is not a percentage, and the weights and variables differ between problems, so the values do not rank the three solvers.

Each order comes from a pair of resolutions, p = log₂(Ecoarse/Efine). An order near one means the error roughly halves when the spacing halves; near two, it falls to about a quarter.

Reported performance, with its workload

18.9% faster Kinetic solve

The velocity-diffusion matrix never changes during a Kinetic run, so I factorise it once and reuse the LU factors instead of refactorising every step. On the standard run, median wall time fell from 267.5 to 217.0 ms (1.23×).

Standard run · 161 × 161 grid, six saved frames
Refactorise267.5 ms
Reuse factors217.0 ms
Saving every step · 81 × 81 grid, 90 saved frames
Refactorise384.7 ms
Reuse factors397.3 ms

When every step is saved, CSV output dominates and reuse is slightly slower (384.7 → 397.3 ms). These are dated native timings on one machine, not browser performance or a general speedup claim.

Benchmark precision and protocol

Recorded 30 September 2026 on an Apple M4 MacBook Air, 24 GB, 10 cores; Apple Clang 21, OpenBLAS 0.3.31, −O2 and one BLAS thread. Each mode had one warm-up and five measured repetitions. Median [Q1, Q3] in milliseconds; the quartiles describe the middle half of five repetitions, not a confidence interval.

161 × 161 · six frames · legacy
267.509 [263.669, 277.595] ms
81 × 81 · 90 frames · legacy
384.703 [382.119, 385.427] ms
161 × 161 · six frames · reuse
217.009 [208.452, 237.429] ms
81 × 81 · 90 frames · reuse
397.334 [368.216, 413.959] ms

Standard workload: 178 steps and snapshot stride 44. Both workloads use C = 0.1, zero force and final t = 1; the minimum request was 80 steps and CFL selection gives the actual counts. Ratios of medians: 1.233× for the standard case and 0.968× for frequent output, where median CSV output in the reuse run was 382.894 ms (96.4% of median total time). C flags -O2 -std=c99 -Wall -Wextra -Wpedantic on macOS 26.6.2 arm64.

What the checks establish

Mathematical reference validation

Independent analytical or discrete references test specified problems, including refinement tests and invariant checks. Not every study yields a convergence order.

Regression agreement

Comparison with earlier outputs checks whether behaviour changed. In the benchmark, the legacy and reuse outputs matched byte-for-byte for all four documented workloads: evidence of equivalence for those inputs, not of independent accuracy.

Discrete-balance checks

Four cases check that changes in integrated fields match recorded sources, transfers and boundary exchange. A small residual shows the accounting is right; it can coexist with a visibly inaccurate field.

Still unvalidated: combined Kinetic splitting, injection-front convergence and variable-diffusion or advective River continuum accuracy. The selected errors are not error bars for the experiment figures.

Origins

From coursework to a toolkit.

PhaseFlow started as my university assignments 3, 4 and 5: separate Transport, River and Kinetic programs, with band-matrix helpers shared by River and Kinetic. I combined them into one executable and built the testing, diagnostics, optimisation and explorer around them. The example inputs are reconstructed, because the original input files were not kept. LAPACK, BLAS and LAPACKE provide the linear algebra.