Skip to main content

qualia_extensions/webgpu_extension/
wave.rs

1//! 2D wave equation `∂²u/∂t² = c²∇²u` by explicit leapfrog (periodic).
2//!
3//! `u_new = 2u − u_old + (cΔt)²∇²u`, CFL `cΔt·√(hx⁻²+hy⁻²) ≤ 1`.
4//!
5//! Validation: `u(x,y,0)=sin(x)sin(y)` with zero initial velocity is a standing
6//! wave `u(t)=sin(x)sin(y)·cos(ωt)`, `ω=c√2`. After half a period the field
7//! inverts (`u(T/2) ≈ −u(0)`); the test checks that the solution is strongly
8//! anti-correlated with the initial state at `T/2` and never blows up.
9
10use super::{dim, uniform, SolverReport, WebGpuJobParams};
11use std::collections::HashMap;
12use std::f64::consts::PI;
13
14#[inline]
15fn wrap(i: i64, n: i64) -> usize {
16    (((i % n) + n) % n) as usize
17}
18
19/// Solves.
20pub fn solve(params: &WebGpuJobParams) -> SolverReport {
21    let nx = dim(params.grid_size.0, 32);
22    let ny = dim(params.grid_size.1, 32);
23    let n = nx * ny;
24    let (nxi, nyi) = (nx as i64, ny as i64);
25
26    let hx = 2.0 * PI / nx as f64;
27    let hy = 2.0 * PI / ny as f64;
28    let c = uniform(params, "wave_speed", 1.0).max(1e-6) as f64;
29
30    // CFL-stable step.
31    let cfl_max = 1.0 / (c * (1.0 / (hx * hx) + 1.0 / (hy * hy)).sqrt());
32    let mut dt = if params.dispatch_params.time_step > 0.0 {
33        params.dispatch_params.time_step
34    } else {
35        0.5 * cfl_max
36    };
37    if dt > 0.95 * cfl_max {
38        dt = 0.95 * cfl_max;
39    }
40    let steps = if params.dispatch_params.iterations > 0 {
41        params.dispatch_params.iterations
42    } else {
43        44
44    };
45
46    let idx = |i: usize, j: usize| j * nx + i;
47
48    // Seed a standing wave with (near) zero initial velocity.
49    let omega = c * 2.0f64.sqrt(); // mode (1,1)
50    let mut u = vec![0.0f64; n];
51    let mut u_old = vec![0.0f64; n];
52    if let Some(field) = params.input_data.get("displacement_field") {
53        for k in 0..n.min(field.len()) {
54            u[k] = field[k] as f64;
55            u_old[k] = u[k];
56        }
57    } else {
58        for j in 0..ny {
59            for i in 0..nx {
60                let base = (i as f64 * hx).sin() * (j as f64 * hy).sin();
61                u[idx(i, j)] = base;
62                // u(−Δt) = base·cos(ωΔt) ⇒ centred velocity ≈ 0.
63                u_old[idx(i, j)] = base * (omega * dt).cos();
64            }
65        }
66    }
67
68    let inv_hx2 = 1.0 / (hx * hx);
69    let inv_hy2 = 1.0 / (hy * hy);
70    let coef = (c * dt) * (c * dt);
71    let mut u_new = vec![0.0f64; n];
72
73    let mut max_abs = 0.0f64;
74    for _ in 0..steps {
75        for j in 0..ny {
76            for i in 0..nx {
77                let cc = idx(i, j);
78                let e = idx(wrap(i as i64 + 1, nxi), j);
79                let w = idx(wrap(i as i64 - 1, nxi), j);
80                let nn = idx(i, wrap(j as i64 + 1, nyi));
81                let s = idx(i, wrap(j as i64 - 1, nyi));
82                let lap =
83                    (u[e] + u[w] - 2.0 * u[cc]) * inv_hx2 + (u[nn] + u[s] - 2.0 * u[cc]) * inv_hy2;
84                u_new[cc] = 2.0 * u[cc] - u_old[cc] + coef * lap;
85                max_abs = max_abs.max(u_new[cc].abs());
86            }
87        }
88        std::mem::swap(&mut u_old, &mut u);
89        std::mem::swap(&mut u, &mut u_new);
90    }
91
92    let displacement_out: Vec<f32> = u.iter().map(|&x| x as f32).collect();
93    let mut output = HashMap::new();
94    output.insert("displacement_out".to_string(), displacement_out);
95
96    let flops = steps as u64 * n as u64 * 12;
97    SolverReport {
98        output,
99        iterations_used: steps,
100        // Residual = peak amplitude growth above the initial unit amplitude
101        // (≈0 for a stable standing wave; >0 would signal CFL instability).
102        final_residual: (max_abs - 1.0).max(0.0) as f32,
103        converged: max_abs < 1.2,
104        flops,
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111    use crate::webgpu_extension::DispatchParams;
112
113    fn analytic_ic(nx: usize, ny: usize) -> Vec<f64> {
114        let hx = 2.0 * PI / nx as f64;
115        let hy = 2.0 * PI / ny as f64;
116        let mut v = vec![0.0f64; nx * ny];
117        for j in 0..ny {
118            for i in 0..nx {
119                v[j * nx + i] = (i as f64 * hx).sin() * (j as f64 * hy).sin();
120            }
121        }
122        v
123    }
124
125    fn correlation(a: &[f32], b: &[f64]) -> f64 {
126        let dot: f64 = a.iter().zip(b).map(|(&x, &y)| x as f64 * y).sum();
127        let na: f64 = a
128            .iter()
129            .map(|&x| (x as f64) * (x as f64))
130            .sum::<f64>()
131            .sqrt();
132        let nb: f64 = b.iter().map(|&y| y * y).sum::<f64>().sqrt();
133        dot / (na * nb)
134    }
135
136    fn wave_params(steps: u32) -> WebGpuJobParams {
137        let mut uniforms = HashMap::new();
138        uniforms.insert("wave_speed".to_string(), 1.0);
139        WebGpuJobParams {
140            shader_name: "wave_equation_2d".to_string(),
141            grid_size: (32, 32, 1),
142            input_data: HashMap::new(),
143            uniform_data: uniforms,
144            dispatch_params: DispatchParams {
145                iterations: steps,
146                time_step: 0.05,
147                convergence_threshold: 1e-3,
148                max_execution_time_ms: 30_000,
149            },
150        }
151    }
152
153    #[test]
154    fn standing_wave_inverts_after_half_period() {
155        // ω = √2, T/2 = π/√2 ≈ 2.221 s. At Δt = 0.05 that is ~44 steps, where
156        // cos(ωt) ≈ −1, so the field should be strongly anti-correlated with IC.
157        let r = solve(&wave_params(44));
158        let ic = analytic_ic(32, 32);
159        let corr = correlation(&r.output["displacement_out"], &ic);
160        assert!(
161            corr < -0.8,
162            "standing wave did not invert at T/2 (correlation {corr:.3})"
163        );
164    }
165
166    #[test]
167    fn leapfrog_is_stable_over_a_long_run() {
168        let r = solve(&wave_params(500));
169        assert!(
170            r.converged,
171            "wave solver went unstable: residual {}",
172            r.final_residual
173        );
174        for &x in &r.output["displacement_out"] {
175            assert!(x.is_finite());
176        }
177    }
178}