Skip to main content

qualia_extensions/webgpu_extension/
fluid.rs

1//! Incompressible 2D Navier–Stokes (periodic) via Chorin's projection method.
2//!
3//! Each step: advect + diffuse to an intermediate velocity `u*`, solve the
4//! pressure-Poisson equation `∇²p = (1/Δt)∇·u*` (Jacobi), then project
5//! `u = u* − Δt∇p` so the field stays divergence-free.
6//!
7//! Validation: the **Taylor–Green vortex** is an exact solution of the
8//! incompressible NS equations whose amplitude decays as `exp(-2νt)` (the
9//! nonlinear advection is exactly balanced by the pressure gradient, leaving
10//! pure viscous diffusion). The unit test reproduces that decay rate.
11
12use super::{dim, uniform, SolverReport, WebGpuJobParams};
13use std::collections::HashMap;
14use std::f64::consts::PI;
15
16#[inline]
17fn wrap(i: i64, n: i64) -> usize {
18    (((i % n) + n) % n) as usize
19}
20
21/// Solves.
22pub fn solve(params: &WebGpuJobParams) -> SolverReport {
23    let nx = dim(params.grid_size.0, 32);
24    let ny = dim(params.grid_size.1, 32);
25    let n = nx * ny;
26    let (nxi, nyi) = (nx as i64, ny as i64);
27
28    let lx = 2.0 * PI;
29    let ly = 2.0 * PI;
30    let hx = lx / nx as f64;
31    let hy = ly / ny as f64;
32
33    let nu = uniform(params, "viscosity", 0.05).max(0.0) as f64;
34    let mut dt = if params.dispatch_params.time_step > 0.0 {
35        params.dispatch_params.time_step
36    } else {
37        0.01
38    };
39    // Explicit-diffusion stability: Δt ≤ 0.25·min(hx,hy)² / ν.
40    if nu > 0.0 {
41        let dt_max = 0.25 * hx.min(hy).powi(2) / nu;
42        if dt > dt_max {
43            dt = dt_max;
44        }
45    }
46    let steps = if params.dispatch_params.iterations > 0 {
47        params.dispatch_params.iterations
48    } else {
49        50
50    };
51
52    let idx = |i: usize, j: usize| j * nx + i;
53
54    // Initial condition: caller-provided interleaved vec2 field, else the
55    // analytic Taylor–Green vortex.
56    let mut u = vec![0.0f64; n];
57    let mut v = vec![0.0f64; n];
58    if let Some(field) = params.input_data.get("velocity_field") {
59        for k in 0..n.min(field.len() / 2) {
60            u[k] = field[2 * k] as f64;
61            v[k] = field[2 * k + 1] as f64;
62        }
63    } else {
64        for j in 0..ny {
65            for i in 0..nx {
66                let x = i as f64 * hx;
67                let y = j as f64 * hy;
68                u[idx(i, j)] = x.sin() * y.cos();
69                v[idx(i, j)] = -x.cos() * y.sin();
70            }
71        }
72    }
73
74    let mut ustar = vec![0.0f64; n];
75    let mut vstar = vec![0.0f64; n];
76    let mut p = vec![0.0f64; n];
77    let mut p_next = vec![0.0f64; n];
78    let mut rhs = vec![0.0f64; n];
79
80    let inv_hx2 = 1.0 / (hx * hx);
81    let inv_hy2 = 1.0 / (hy * hy);
82    let denom = 2.0 * (inv_hx2 + inv_hy2);
83    let jacobi_iters = 60usize;
84
85    for _ in 0..steps {
86        // 1) Advection (central) + viscous diffusion → intermediate velocity.
87        for j in 0..ny {
88            for i in 0..nx {
89                let c = idx(i, j);
90                let e = idx(wrap(i as i64 + 1, nxi), j);
91                let w = idx(wrap(i as i64 - 1, nxi), j);
92                let nn = idx(i, wrap(j as i64 + 1, nyi));
93                let s = idx(i, wrap(j as i64 - 1, nyi));
94
95                let dudx = (u[e] - u[w]) / (2.0 * hx);
96                let dudy = (u[nn] - u[s]) / (2.0 * hy);
97                let dvdx = (v[e] - v[w]) / (2.0 * hx);
98                let dvdy = (v[nn] - v[s]) / (2.0 * hy);
99
100                let lap_u =
101                    (u[e] + u[w] - 2.0 * u[c]) * inv_hx2 + (u[nn] + u[s] - 2.0 * u[c]) * inv_hy2;
102                let lap_v =
103                    (v[e] + v[w] - 2.0 * v[c]) * inv_hx2 + (v[nn] + v[s] - 2.0 * v[c]) * inv_hy2;
104
105                let adv_u = u[c] * dudx + v[c] * dudy;
106                let adv_v = u[c] * dvdx + v[c] * dvdy;
107
108                ustar[c] = u[c] + dt * (-adv_u + nu * lap_u);
109                vstar[c] = v[c] + dt * (-adv_v + nu * lap_v);
110            }
111        }
112
113        // 2) Pressure-Poisson RHS = (1/Δt)·∇·u*.
114        for j in 0..ny {
115            for i in 0..nx {
116                let e = idx(wrap(i as i64 + 1, nxi), j);
117                let w = idx(wrap(i as i64 - 1, nxi), j);
118                let nn = idx(i, wrap(j as i64 + 1, nyi));
119                let s = idx(i, wrap(j as i64 - 1, nyi));
120                let div = (ustar[e] - ustar[w]) / (2.0 * hx) + (vstar[nn] - vstar[s]) / (2.0 * hy);
121                rhs[idx(i, j)] = div / dt;
122            }
123        }
124
125        // Jacobi solve of ∇²p = rhs (periodic).
126        for it in 0..jacobi_iters {
127            for j in 0..ny {
128                for i in 0..nx {
129                    let c = idx(i, j);
130                    let e = idx(wrap(i as i64 + 1, nxi), j);
131                    let w = idx(wrap(i as i64 - 1, nxi), j);
132                    let nn = idx(i, wrap(j as i64 + 1, nyi));
133                    let s = idx(i, wrap(j as i64 - 1, nyi));
134                    p_next[c] =
135                        ((p[e] + p[w]) * inv_hx2 + (p[nn] + p[s]) * inv_hy2 - rhs[c]) / denom;
136                }
137            }
138            std::mem::swap(&mut p, &mut p_next);
139            // Pin the periodic null space (constant offset) on the last sweep.
140            if it == jacobi_iters - 1 {
141                let mean: f64 = p.iter().sum::<f64>() / n as f64;
142                for pv in p.iter_mut() {
143                    *pv -= mean;
144                }
145            }
146        }
147
148        // 3) Project: u = u* − Δt·∇p.
149        for j in 0..ny {
150            for i in 0..nx {
151                let c = idx(i, j);
152                let e = idx(wrap(i as i64 + 1, nxi), j);
153                let w = idx(wrap(i as i64 - 1, nxi), j);
154                let nn = idx(i, wrap(j as i64 + 1, nyi));
155                let s = idx(i, wrap(j as i64 - 1, nyi));
156                u[c] = ustar[c] - dt * (p[e] - p[w]) / (2.0 * hx);
157                v[c] = vstar[c] - dt * (p[nn] - p[s]) / (2.0 * hy);
158            }
159        }
160    }
161
162    // Residual = max incompressibility error |∇·u| after projection.
163    let mut max_div = 0.0f64;
164    for j in 0..ny {
165        for i in 0..nx {
166            let e = idx(wrap(i as i64 + 1, nxi), j);
167            let w = idx(wrap(i as i64 - 1, nxi), j);
168            let nn = idx(i, wrap(j as i64 + 1, nyi));
169            let s = idx(i, wrap(j as i64 - 1, nyi));
170            let div = (u[e] - u[w]) / (2.0 * hx) + (v[nn] - v[s]) / (2.0 * hy);
171            max_div = max_div.max(div.abs());
172        }
173    }
174
175    let mut velocity_out = Vec::with_capacity(n * 2);
176    for k in 0..n {
177        velocity_out.push(u[k] as f32);
178        velocity_out.push(v[k] as f32);
179    }
180    let mut output = HashMap::new();
181    output.insert("velocity_out".to_string(), velocity_out);
182
183    let threshold = params.dispatch_params.convergence_threshold.max(1e-2);
184    // Per-step cost: ~30 FLOPs/cell (advect+diffuse) + jacobi sweeps + project.
185    let flops = steps as u64 * n as u64 * (30 + jacobi_iters as u64 * 8 + 8);
186
187    SolverReport {
188        output,
189        iterations_used: steps,
190        final_residual: max_div as f32,
191        converged: (max_div as f32) <= threshold,
192        flops,
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::webgpu_extension::DispatchParams;
200
201    fn rms(field: &[f32]) -> f64 {
202        let s: f64 = field.iter().map(|&x| (x as f64) * (x as f64)).sum();
203        (s / field.len() as f64).sqrt()
204    }
205
206    fn tg_params(nu: f32, dt: f64, steps: u32) -> WebGpuJobParams {
207        let mut uniforms = HashMap::new();
208        uniforms.insert("viscosity".to_string(), nu);
209        WebGpuJobParams {
210            shader_name: "navier_stokes_2d".to_string(),
211            grid_size: (32, 32, 1),
212            input_data: HashMap::new(),
213            uniform_data: uniforms,
214            dispatch_params: DispatchParams {
215                iterations: steps,
216                time_step: dt,
217                convergence_threshold: 0.1,
218                max_execution_time_ms: 30_000,
219            },
220        }
221    }
222
223    #[test]
224    fn taylor_green_vortex_decays_at_analytic_rate() {
225        // ν = 0.5, Δt = 0.01, 50 steps ⇒ t = 0.5; analytic amplitude ratio is
226        // exp(-2·ν·t) = exp(-0.5) ≈ 0.6065. Initial TG RMS = sqrt(1/2) ≈ 0.7071.
227        let nu = 0.5;
228        let dt = 0.01;
229        let steps = 50;
230        let r = solve(&tg_params(nu, dt, steps));
231
232        let final_rms = rms(&r.output["velocity_out"]);
233        let t = dt * steps as f64;
234        // RMS over the interleaved (u,v) array = sqrt((mean u² + mean v²)/2)
235        // = sqrt((1/4 + 1/4)/... ) = 0.5 for the unit-amplitude TG vortex.
236        let expected = 0.5 * (-2.0 * nu as f64 * t).exp();
237
238        let rel_err = (final_rms - expected).abs() / expected;
239        assert!(
240            rel_err < 0.06,
241            "TG decay off: got rms {final_rms:.5}, expected {expected:.5} (rel {rel_err:.3})"
242        );
243    }
244
245    #[test]
246    fn projection_keeps_the_field_divergence_free() {
247        let r = solve(&tg_params(0.5, 0.01, 50));
248        assert!(
249            r.final_residual < 0.1,
250            "incompressibility residual too large: {}",
251            r.final_residual
252        );
253        assert!(r.converged);
254    }
255
256    #[test]
257    fn inviscid_vortex_barely_decays() {
258        // With ν = 0 the Taylor–Green amplitude should be (nearly) conserved.
259        let r = solve(&tg_params(0.0, 0.005, 40));
260        let final_rms = rms(&r.output["velocity_out"]);
261        let init = 0.5; // interleaved-array RMS of the unit-amplitude TG vortex
262        assert!(
263            (final_rms - init).abs() / init < 0.05,
264            "inviscid amplitude drifted: {final_rms:.5} vs {init:.5}"
265        );
266    }
267}