Skip to main content

qualia_extensions/webgpu_extension/
electromagnetics.rs

1//! 1D electromagnetics by the **Yee FDTD** scheme (the canonical, validatable
2//! Maxwell solver).
3//!
4//! `E_y` and `H_z` are staggered in space and leap-frogged in time:
5//! ```text
6//! Hz[i] += (Δt/μΔx)·(Ey[i+1] − Ey[i])
7//! Ey[i] += (Δt/εΔx)·(Hz[i] − Hz[i-1]) − (Δt·σ/ε)·Ey[i]
8//! ```
9//! with the Courant number `c·Δt/Δx ≤ 1`. Fields are stored in the 3-vector
10//! layout `E = (0, Ey, 0)`, `H = (0, 0, Hz)` (`electric_out` / `magnetic_out`).
11//!
12//! Validation: an impedance-matched pulse (`Hz = Ey/η`) is a pure right-moving
13//! wave; the test checks it travels the analytic distance `c·Δt·N/Δx` and that
14//! the lossless field energy stays bounded.
15
16use super::{dim, uniform, SolverReport, WebGpuJobParams};
17use std::collections::HashMap;
18
19/// Solves.
20pub fn solve(params: &WebGpuJobParams) -> SolverReport {
21    let n = dim(params.grid_size.0, 200);
22    let dx = 1.0f64;
23    let eps = uniform(params, "epsilon", 1.0).max(1e-6) as f64;
24    let mu = uniform(params, "mu", 1.0).max(1e-6) as f64;
25    let sigma = uniform(params, "sigma", 0.0).max(0.0) as f64;
26    let c = 1.0 / (eps * mu).sqrt();
27
28    // Courant-stable time step (Sc = 0.5 keeps a clean integer cell speed).
29    let courant = 0.5;
30    let dt = courant * dx / c;
31    let steps = if params.dispatch_params.iterations > 0 {
32        params.dispatch_params.iterations
33    } else {
34        100
35    };
36
37    let eta = (mu / eps).sqrt(); // wave impedance
38
39    let mut ey = vec![0.0f64; n];
40    let mut hz = vec![0.0f64; n];
41
42    if let (Some(ein), Some(hin)) = (
43        params.input_data.get("electric_field"),
44        params.input_data.get("magnetic_field"),
45    ) {
46        // Caller fields are 3-vectors: read the y/z components.
47        for i in 0..n.min(ein.len() / 3) {
48            ey[i] = ein[3 * i + 1] as f64;
49        }
50        for i in 0..n.min(hin.len() / 3) {
51            hz[i] = hin[3 * i + 2] as f64;
52        }
53    } else {
54        // Impedance-matched Gaussian pulse → pure +x traveling wave.
55        let x0 = n as f64 * 0.25;
56        let width = n as f64 / 16.0;
57        for i in 0..n {
58            let arg = (i as f64 - x0) / width;
59            let g = (-arg * arg).exp();
60            ey[i] = g;
61            hz[i] = g / eta;
62        }
63    }
64
65    let energy = |ey: &[f64], hz: &[f64]| -> f64 {
66        0.5 * (0..n)
67            .map(|i| eps * ey[i] * ey[i] + mu * hz[i] * hz[i])
68            .sum::<f64>()
69    };
70    let e0 = energy(&ey, &hz);
71
72    let ch = dt / (mu * dx);
73    let a = 0.5 * sigma * dt / eps;
74
75    // Maxwell's curl equations: μ∂Hz/∂t = −∂Ey/∂x, ε∂Ey/∂t = −∂Hz/∂x − σEy.
76    // Schneider's unconditionally stable semi-implicit update for conductive media.
77    for _ in 0..steps {
78        for i in 0..n {
79            let ip1 = if i + 1 < n { i + 1 } else { 0 };
80            hz[i] -= ch * (ey[ip1] - ey[i]);
81        }
82        for i in 0..n {
83            let im1 = if i == 0 { n - 1 } else { i - 1 };
84            ey[i] = ((1.0 - a) / (1.0 + a)) * ey[i]
85                - ((dt / (eps * dx)) / (1.0 + a)) * (hz[i] - hz[im1]);
86        }
87    }
88
89    let e1 = energy(&ey, &hz);
90
91    let mut electric_out = Vec::with_capacity(n * 3);
92    let mut magnetic_out = Vec::with_capacity(n * 3);
93    for i in 0..n {
94        electric_out.extend_from_slice(&[0.0, ey[i] as f32, 0.0]);
95        magnetic_out.extend_from_slice(&[0.0, 0.0, hz[i] as f32]);
96    }
97    let mut output = HashMap::new();
98    output.insert("electric_out".to_string(), electric_out);
99    output.insert("magnetic_out".to_string(), magnetic_out);
100
101    // Residual: relative energy change (≈0 in the lossless case).
102    let residual = if e0 > 0.0 {
103        ((e1 - e0) / e0).abs() as f32
104    } else {
105        0.0
106    };
107    let threshold = params.dispatch_params.convergence_threshold.max(0.1);
108    let flops = steps as u64 * n as u64 * 8;
109
110    SolverReport {
111        output,
112        iterations_used: steps,
113        final_residual: residual,
114        converged: e1.is_finite() && residual <= threshold,
115        flops,
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use crate::webgpu_extension::DispatchParams;
123
124    fn em_params(n: u32, steps: u32, sigma: f32) -> WebGpuJobParams {
125        let mut uniforms = HashMap::new();
126        uniforms.insert("epsilon".to_string(), 1.0);
127        uniforms.insert("mu".to_string(), 1.0);
128        uniforms.insert("sigma".to_string(), sigma);
129        WebGpuJobParams {
130            shader_name: "maxwell_fdtd_1d".to_string(),
131            grid_size: (n, 1, 1),
132            input_data: HashMap::new(),
133            uniform_data: uniforms,
134            dispatch_params: DispatchParams {
135                iterations: steps,
136                time_step: 0.0,
137                convergence_threshold: 0.1,
138                max_execution_time_ms: 30_000,
139            },
140        }
141    }
142
143    fn peak_index(field: &[f32]) -> usize {
144        // field is 3-vector; the Ey component is index 3*i + 1.
145        let n = field.len() / 3;
146        let mut best = 0usize;
147        let mut best_v = f32::MIN;
148        for i in 0..n {
149            let v = field[3 * i + 1];
150            if v > best_v {
151                best_v = v;
152                best = i;
153            }
154        }
155        best
156    }
157
158    #[test]
159    fn pulse_propagates_at_the_speed_of_light() {
160        // c = 1, Sc = 0.5 ⇒ pulse advances 0.5 cells/step. 100 steps ⇒ 50 cells.
161        let n = 200u32;
162        let steps = 100u32;
163        let r = solve(&em_params(n, steps, 0.0));
164        let peak = peak_index(&r.output["electric_out"]);
165        let start = (n as f64 * 0.25) as usize; // 50
166        let expected = start + 50; // 100
167        assert!(
168            (peak as i64 - expected as i64).abs() <= 3,
169            "pulse peak at {peak}, expected ~{expected}"
170        );
171    }
172
173    #[test]
174    fn lossless_energy_is_bounded() {
175        // The same-time Yee energy oscillates by a small amount (E and H live on
176        // staggered time levels); for a well-resolved pulse it stays within a
177        // few percent. The precise physics check is `propagates_at_c` above.
178        let r = solve(&em_params(200, 100, 0.0));
179        assert!(
180            r.final_residual < 0.1,
181            "lossless energy drifted by {}",
182            r.final_residual
183        );
184        assert!(r.converged);
185    }
186
187    fn field_energy(report: &SolverReport) -> f64 {
188        let e = &report.output["electric_out"];
189        let h = &report.output["magnetic_out"];
190        let n = e.len() / 3;
191        0.5 * (0..n)
192            .map(|i| {
193                let ey = e[3 * i + 1] as f64;
194                let hz = h[3 * i + 2] as f64;
195                ey * ey + hz * hz
196            })
197            .sum::<f64>()
198    }
199
200    fn initial_gaussian_energy(n: usize) -> f64 {
201        let x0 = n as f64 * 0.25;
202        let width = n as f64 / 16.0;
203        0.5 * (0..n)
204            .map(|i| {
205                let arg = (i as f64 - x0) / width;
206                let g = (-arg * arg).exp();
207                g * g + g * g
208            })
209            .sum::<f64>()
210    }
211
212    #[test]
213    fn lossy_medium_dissipates_energy() {
214        let e0 = initial_gaussian_energy(200);
215        let r = solve(&em_params(200, 200, 0.05));
216        let e1 = field_energy(&r);
217        assert!(e1.is_finite(), "lossy field energy must be finite");
218        assert!(
219            e1 < e0,
220            "signed energy dissipation required: e1 ({e1}) must be strictly less than e0 ({e0})"
221        );
222        // Conductivity must remove a large fraction of the energy.
223        assert!(
224            r.final_residual > 0.2,
225            "lossy run did not dissipate energy (residual {})",
226            r.final_residual
227        );
228
229        // Semi-implicit Yee stability check for high conductivity (dt * sigma / eps > 2.0).
230        let r_high_sigma = solve(&em_params(200, 200, 10.0));
231        let e1_high = field_energy(&r_high_sigma);
232        assert!(e1_high.is_finite(), "semi-implicit update must remain finite at high sigma");
233        assert!(
234            e1_high < e0,
235            "high-conductivity run must strictly dissipate energy: e1_high ({e1_high}) < e0 ({e0})"
236        );
237    }
238}