1use super::schemas::{i64_at, ConstitutiveKind};
5use super::*;
6use core::f64::consts::{FRAC_1_SQRT_2, PI, SQRT_2};
7
8pub const YEE_PROFILE: &str = "yee_cartesian_v1";
9pub const YEE_MODEL_URI: &str = "urn:qualia:emf:yee_cartesian_v1";
10
11pub const SPEED_OF_LIGHT_M_PER_S: f64 = 299_792_458.0;
12pub const VACUUM_PERMEABILITY_H_PER_M: f64 = 4.0 * PI * 1.0e-7;
13pub const VACUUM_PERMITTIVITY_F_PER_M: f64 =
14 1.0 / (VACUUM_PERMEABILITY_H_PER_M * SPEED_OF_LIGHT_M_PER_S * SPEED_OF_LIGHT_M_PER_S);
15pub const VACUUM_IMPEDANCE_OHM: f64 = VACUUM_PERMEABILITY_H_PER_M * SPEED_OF_LIGHT_M_PER_S;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum PhasorAmplitudeKind {
19 Peak,
20 Rms,
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum HarmonicSign {
25 MinusIwt,
26 PlusIwt,
27}
28
29impl HarmonicSign {
30 pub const fn sign_factor(self) -> f64 {
31 match self {
32 Self::MinusIwt => -1.0,
33 Self::PlusIwt => 1.0,
34 }
35 }
36}
37
38#[inline]
39pub fn rms_to_peak(rms: f64) -> f64 {
40 rms * SQRT_2
41}
42
43#[inline]
44pub fn peak_to_rms(peak: f64) -> f64 {
45 peak * FRAC_1_SQRT_2
46}
47
48pub fn evaluate_instantaneous_phasor(
50 phasor_re: [f64; 3],
51 phasor_im: [f64; 3],
52 omega_rad_s: f64,
53 t_s: f64,
54 amplitude: PhasorAmplitudeKind,
55 sign: HarmonicSign,
56) -> Result<[f64; 3], Error> {
57 if !omega_rad_s.is_finite()
58 || !t_s.is_finite()
59 || phasor_re.iter().any(|v| !v.is_finite())
60 || phasor_im.iter().any(|v| !v.is_finite())
61 {
62 return Err(Error::NonFinite);
63 }
64 if omega_rad_s < 0.0 {
65 return Err(Error::Value);
66 }
67 let scale = match amplitude {
68 PhasorAmplitudeKind::Peak => 1.0,
69 PhasorAmplitudeKind::Rms => SQRT_2,
70 };
71 let theta = sign.sign_factor() * omega_rad_s * t_s;
72 let (s_th, c_th) = theta.sin_cos();
73 Ok([
74 scale * (phasor_re[0] * c_th - phasor_im[0] * s_th),
75 scale * (phasor_re[1] * c_th - phasor_im[1] * s_th),
76 scale * (phasor_re[2] * c_th - phasor_im[2] * s_th),
77 ])
78}
79
80#[inline]
81pub fn poynting_e_cross_h(e: [f64; 3], h: [f64; 3]) -> [f64; 3] {
82 [
83 e[1] * h[2] - e[2] * h[1],
84 e[2] * h[0] - e[0] * h[2],
85 e[0] * h[1] - e[1] * h[0],
86 ]
87}
88
89#[inline]
90pub fn poynting_from_eb_vacuum(e: [f64; 3], b: [f64; 3]) -> [f64; 3] {
91 let inv_mu0 = 1.0 / VACUUM_PERMEABILITY_H_PER_M;
92 poynting_e_cross_h(e, [b[0] * inv_mu0, b[1] * inv_mu0, b[2] * inv_mu0])
93}
94
95pub fn energy_density_isotropic(
96 e: [f64; 3],
97 h: [f64; 3],
98 eps_r: f64,
99 mu_r: f64,
100) -> Result<f64, Error> {
101 if e.iter().any(|v| !v.is_finite())
102 || h.iter().any(|v| !v.is_finite())
103 || !eps_r.is_finite()
104 || !mu_r.is_finite()
105 {
106 return Err(Error::NonFinite);
107 }
108 if eps_r <= 0.0 || mu_r <= 0.0 {
109 return Err(Error::Value);
110 }
111 let e2 = e[0] * e[0] + e[1] * e[1] + e[2] * e[2];
112 let h2 = h[0] * h[0] + h[1] * h[1] + h[2] * h[2];
113 Ok(0.5 * (VACUUM_PERMITTIVITY_F_PER_M * eps_r * e2 + VACUUM_PERMEABILITY_H_PER_M * mu_r * h2))
114}
115
116#[inline]
117pub fn energy_density_vacuum_eb(e: [f64; 3], b: [f64; 3]) -> Result<f64, Error> {
118 if e.iter().any(|v| !v.is_finite()) || b.iter().any(|v| !v.is_finite()) {
119 return Err(Error::NonFinite);
120 }
121 let e2 = e[0] * e[0] + e[1] * e[1] + e[2] * e[2];
122 let b2 = b[0] * b[0] + b[1] * b[1] + b[2] * b[2];
123 Ok(0.5 * (VACUUM_PERMITTIVITY_F_PER_M * e2 + b2 / VACUUM_PERMEABILITY_H_PER_M))
124}
125
126#[derive(Clone, Copy, Debug, PartialEq)]
128pub struct JonesVector {
129 pub ex_re: f64,
130 pub ex_im: f64,
131 pub ey_re: f64,
132 pub ey_im: f64,
133}
134
135impl JonesVector {
136 pub fn to_stokes(self, scale_irradiance: f64) -> Result<[f64; 4], Error> {
138 if !self.ex_re.is_finite()
139 || !self.ex_im.is_finite()
140 || !self.ey_re.is_finite()
141 || !self.ey_im.is_finite()
142 || !scale_irradiance.is_finite()
143 {
144 return Err(Error::NonFinite);
145 }
146 if scale_irradiance < 0.0 {
147 return Err(Error::Value);
148 }
149 let ax2 = self.ex_re * self.ex_re + self.ex_im * self.ex_im;
150 let ay2 = self.ey_re * self.ey_re + self.ey_im * self.ey_im;
151 let i = scale_irradiance * (ax2 + ay2);
152 let q = scale_irradiance * (ax2 - ay2);
153 let u = scale_irradiance * 2.0 * (self.ex_re * self.ey_re + self.ex_im * self.ey_im);
154 let v = scale_irradiance * 2.0 * (self.ex_re * self.ey_im - self.ex_im * self.ey_re);
155 Ok([i, q, u, v])
156 }
157}
158
159pub fn rotate_stokes_passive(stokes: [f64; 4], theta_rad: f64) -> Result<[f64; 4], Error> {
161 if stokes.iter().any(|v| !v.is_finite()) || !theta_rad.is_finite() {
162 return Err(Error::NonFinite);
163 }
164 let (s, c) = (2.0 * theta_rad).sin_cos();
165 Ok([
166 stokes[0],
167 stokes[1] * c + stokes[2] * s,
168 -stokes[1] * s + stokes[2] * c,
169 stokes[3],
170 ])
171}
172
173pub fn optical_path_delay_seconds(
174 geometric_path_m: f64,
175 group_refractive_index: f64,
176) -> Result<f64, Error> {
177 if !geometric_path_m.is_finite() || !group_refractive_index.is_finite() {
178 return Err(Error::NonFinite);
179 }
180 if geometric_path_m < 0.0 || group_refractive_index <= 0.0 {
181 return Err(Error::Value);
182 }
183 Ok(geometric_path_m * group_refractive_index / SPEED_OF_LIGHT_M_PER_S)
184}
185
186#[derive(Clone, Copy, Debug, PartialEq)]
187pub struct YeeRecord {
188 pub electric_field_v_per_m: [f64; 3],
189 pub magnetic_field_h_a_per_m: [f64; 3],
190 pub impressed_current_j_a_per_m2: [f64; 3],
191 pub scalar_potential_v: f64,
192 pub charge_density_c_per_m3: f64,
193 pub epsilon_relative: f64,
194 pub mu_relative: f64,
195 pub conductivity_s_per_m: f64,
196 pub material_entry: u32,
197 pub constitutive_metadata_id: u32,
198 pub state_record_index: u64,
199}
200
201#[derive(Clone, Copy, Debug)]
202pub struct YeeParsePolicy {
203 pub require_no_phi_placeholder: bool,
204 pub require_charge_free: bool,
205 pub expected_constitutive_id: Option<u32>,
206 pub has_auxiliary_state_streams: bool,
207}
208
209impl Default for YeeParsePolicy {
210 fn default() -> Self {
211 Self {
212 require_no_phi_placeholder: true,
213 require_charge_free: false,
214 expected_constitutive_id: None,
215 has_auxiliary_state_streams: false,
216 }
217 }
218}
219
220impl YeeRecord {
221 pub fn vacuum(
222 e: [f64; 3],
223 h: [f64; 3],
224 constitutive_metadata_id: u32,
225 ) -> Self {
226 Self {
227 electric_field_v_per_m: e,
228 magnetic_field_h_a_per_m: h,
229 impressed_current_j_a_per_m2: [0.0; 3],
230 scalar_potential_v: 0.0,
231 charge_density_c_per_m3: 0.0,
232 epsilon_relative: 1.0,
233 mu_relative: 1.0,
234 conductivity_s_per_m: 0.0,
235 material_entry: 0,
236 constitutive_metadata_id,
237 state_record_index: u64::MAX,
238 }
239 }
240
241 pub fn parse(
242 bytes: &[u8],
243 valid: bool,
244 policy: YeeParsePolicy,
245 ) -> Result<Option<Self>, Error> {
246 if bytes.len() != 128 {
247 return Err(Error::Shape);
248 }
249 if !valid {
250 zeros(bytes)?;
251 return Ok(None);
252 }
253 finite(bytes, 0, 112)?;
254 let phi = f64_at(bytes, 72);
255 let rho = f64_at(bytes, 80);
256 let eps_r = f64_at(bytes, 88);
257 let mu_r = f64_at(bytes, 96);
258 let sigma = f64_at(bytes, 104);
259 if eps_r <= 0.0 || mu_r <= 0.0 || sigma < 0.0 {
260 return Err(Error::Value);
261 }
262 if policy.require_no_phi_placeholder && phi.to_bits() != 0 {
263 return Err(Error::Reserved);
264 }
265 if policy.require_charge_free && rho != 0.0 {
266 return Err(Error::Value);
267 }
268 let material_entry = u32_at(bytes, 112);
269 let constitutive_metadata_id = u32_at(bytes, 116);
270 let state_record_index = u64_at(bytes, 120);
271 if let Some(expected_id) = policy.expected_constitutive_id {
272 if constitutive_metadata_id != expected_id {
273 return Err(Error::Descriptor);
274 }
275 }
276 if !policy.has_auxiliary_state_streams && state_record_index != u64::MAX {
277 return Err(Error::Index);
278 }
279 Ok(Some(Self {
280 electric_field_v_per_m: triple(bytes, 0),
281 magnetic_field_h_a_per_m: triple(bytes, 24),
282 impressed_current_j_a_per_m2: triple(bytes, 48),
283 scalar_potential_v: phi,
284 charge_density_c_per_m3: rho,
285 epsilon_relative: eps_r,
286 mu_relative: mu_r,
287 conductivity_s_per_m: sigma,
288 material_entry,
289 constitutive_metadata_id,
290 state_record_index,
291 }))
292 }
293
294 pub fn encode(&self, valid: bool, out: &mut [u8; 128]) -> Result<(), Error> {
295 *out = [0u8; 128];
296 if !valid {
297 return Ok(());
298 }
299 let all_f64 = [
300 self.electric_field_v_per_m[0],
301 self.electric_field_v_per_m[1],
302 self.electric_field_v_per_m[2],
303 self.magnetic_field_h_a_per_m[0],
304 self.magnetic_field_h_a_per_m[1],
305 self.magnetic_field_h_a_per_m[2],
306 self.impressed_current_j_a_per_m2[0],
307 self.impressed_current_j_a_per_m2[1],
308 self.impressed_current_j_a_per_m2[2],
309 self.scalar_potential_v,
310 self.charge_density_c_per_m3,
311 self.epsilon_relative,
312 self.mu_relative,
313 self.conductivity_s_per_m,
314 ];
315 if all_f64.iter().any(|v| !v.is_finite()) {
316 return Err(Error::NonFinite);
317 }
318 if self.epsilon_relative <= 0.0 || self.mu_relative <= 0.0 || self.conductivity_s_per_m < 0.0
319 {
320 return Err(Error::Value);
321 }
322 for (i, v) in all_f64.iter().enumerate() {
323 out[i * 8..i * 8 + 8].copy_from_slice(&v.to_le_bytes());
324 }
325 out[112..116].copy_from_slice(&self.material_entry.to_le_bytes());
326 out[116..120].copy_from_slice(&self.constitutive_metadata_id.to_le_bytes());
327 out[120..128].copy_from_slice(&self.state_record_index.to_le_bytes());
328 Ok(())
329 }
330}
331
332pub fn encode_yee_records(
333 records: &[YeeRecord],
334 valid: Option<&[bool]>,
335 out: &mut [u8],
336) -> Result<usize, Error> {
337 if let Some(v) = valid {
338 if v.len() != records.len() {
339 return Err(Error::Shape);
340 }
341 }
342 let needed = records.len().checked_mul(128).ok_or(Error::Overflow)?;
343 if out.len() < needed {
344 return Err(Error::Shape);
345 }
346 for (idx, rec) in records.iter().enumerate() {
347 let is_valid = valid.is_none_or(|v| v[idx]);
348 let dst: &mut [u8; 128] = (&mut out[idx * 128..idx * 128 + 128])
349 .try_into()
350 .map_err(|_| Error::Shape)?;
351 rec.encode(is_valid, dst)?;
352 }
353 Ok(needed)
354}
355
356pub fn validate_yee_extension(ext: Block<'_>, frame: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), Error> {
359 if [5, 6].iter().any(|&k| field(frame, k).is_none()) {
360 return Err(Error::Frame);
361 }
362 let _ = spatial::from_metadata(frame, ext)?;
363 let f_const = required(ext, 14)?;
364 if f_const.flags() & 1 == 0 {
365 return Err(Error::Descriptor);
366 }
367 let const_block = ctx
368 .require_schema(u32_at(f_const.value(), 0), 133)
369 .map_err(Error::Shared)?;
370 let kind = ConstitutiveKind::parse(text(required(const_block, 1)?)?)?;
371
372 let aux_entries = field(ext, 26);
374 let bnd_entries = field(ext, 29);
375 if let Some(aux) = aux_entries {
376 if aux.value().is_empty() || !aux.value().len().is_multiple_of(4) {
377 return Err(Error::Descriptor);
378 }
379 for chunk in aux.value().chunks_exact(4) {
380 let _ = ctx.entry(u32_at(chunk, 0)).map_err(Error::Shared)?;
381 }
382 }
383 if let Some(bnd) = bnd_entries {
384 if bnd.value().is_empty() || !bnd.value().len().is_multiple_of(4) {
385 return Err(Error::Descriptor);
386 }
387 for chunk in bnd.value().chunks_exact(4) {
388 let _ = ctx.entry(u32_at(chunk, 0)).map_err(Error::Shared)?;
389 }
390 }
391 match kind {
392 ConstitutiveKind::Vacuum | ConstitutiveKind::IsotropicNondispersive => {}
393 ConstitutiveKind::DebyeIsotropic
394 | ConstitutiveKind::LorentzIsotropic
395 | ConstitutiveKind::AnisotropicTabulated => {
396 if aux_entries.is_none() || bnd_entries.is_none() {
397 return Err(Error::UnsupportedProfile);
398 }
399 }
400 }
401
402 let nums = field(ext, 27);
404 let dens = field(ext, 28);
405 match (nums, dens) {
406 (None, None) => {}
407 (Some(n_f), Some(d_f)) => {
408 if n_f.element_count() != d_f.element_count() || n_f.element_count() < 6 {
409 return Err(Error::Shape);
410 }
411 for i in 0..n_f.element_count() as usize {
412 let num = i64_at(n_f.value(), i * 8);
413 let den = u64_at(d_f.value(), i * 8);
414 if den == 0 || num < 0 {
415 return Err(Error::Time);
416 }
417 if i < 3 && num != 0 {
418 return Err(Error::Time);
419 }
420 if (3..6).contains(&i) && (num == 0 || num as u64 >= den) {
421 return Err(Error::Time);
422 }
423 }
424 }
425 _ => return Err(Error::Time),
426 }
427 Ok(())
428}
429
430pub fn yee_cfl_max_dt_seconds(spacing_m: [f64; 3], eps_r: f64, mu_r: f64) -> Result<f64, Error> {
432 if spacing_m.iter().any(|v| !v.is_finite()) || !eps_r.is_finite() || !mu_r.is_finite() {
433 return Err(Error::NonFinite);
434 }
435 if spacing_m.iter().any(|&v| v <= 0.0) || eps_r <= 0.0 || mu_r <= 0.0 {
436 return Err(Error::Value);
437 }
438 let inv_h2 = 1.0 / (spacing_m[0] * spacing_m[0])
439 + 1.0 / (spacing_m[1] * spacing_m[1])
440 + 1.0 / (spacing_m[2] * spacing_m[2]);
441 let c_mat = SPEED_OF_LIGHT_M_PER_S / (eps_r * mu_r).sqrt();
442 Ok(1.0 / (c_mat * inv_h2.sqrt()))
443}
444
445pub fn yee_check_cfl(
447 dt_s: f64,
448 spacing_m: [f64; 3],
449 eps_r: f64,
450 mu_r: f64,
451) -> Result<f64, Error> {
452 if !dt_s.is_finite() {
453 return Err(Error::NonFinite);
454 }
455 if dt_s <= 0.0 {
456 return Err(Error::Time);
457 }
458 let dt_max = yee_cfl_max_dt_seconds(spacing_m, eps_r, mu_r)?;
459 let s = dt_s / dt_max;
460 if s > 1.0 + 1.0e-12 {
461 return Err(Error::Time);
462 }
463 Ok(s.min(1.0))
464}
465
466pub fn yee_discrete_dispersion_omega(
469 k_rad_per_m: [f64; 3],
470 spacing_m: [f64; 3],
471 dt_s: f64,
472 eps_r: f64,
473 mu_r: f64,
474) -> Result<f64, Error> {
475 if k_rad_per_m.iter().any(|v| !v.is_finite()) {
476 return Err(Error::NonFinite);
477 }
478 let _ = yee_check_cfl(dt_s, spacing_m, eps_r, mu_r)?;
479 let c_mat = SPEED_OF_LIGHT_M_PER_S / (eps_r * mu_r).sqrt();
480 let mut sum = 0.0f64;
481 for i in 0..3 {
482 let s = (0.5 * k_rad_per_m[i] * spacing_m[i]).sin();
483 sum += (s * s) / (spacing_m[i] * spacing_m[i]);
484 }
485 let rhs = (c_mat * dt_s) * (c_mat * dt_s) * sum;
486 if rhs > 1.0 + 1.0e-12 {
487 return Err(Error::Value);
488 }
489 Ok((2.0 / dt_s) * rhs.clamp(0.0, 1.0).sqrt().asin())
490}
491
492#[inline]
493fn cell_idx(x: usize, y: usize, z: usize, dims: [usize; 3]) -> usize {
494 x + dims[0] * (y + dims[1] * z)
495}
496
497pub fn yee_step_periodic(
501 cells: &mut [YeeRecord],
502 dims: [u32; 3],
503 spacing_m: [f64; 3],
504 dt_s: f64,
505) -> Result<(), Error> {
506 let nx = usize::try_from(dims[0]).map_err(|_| Error::Overflow)?;
507 let ny = usize::try_from(dims[1]).map_err(|_| Error::Overflow)?;
508 let nz = usize::try_from(dims[2]).map_err(|_| Error::Overflow)?;
509 if nx == 0 || ny == 0 || nz == 0 {
510 return Err(Error::Shape);
511 }
512 let expected = nx
513 .checked_mul(ny)
514 .and_then(|n| n.checked_mul(nz))
515 .ok_or(Error::Overflow)?;
516 if cells.len() != expected {
517 return Err(Error::Shape);
518 }
519 let d3 = [nx, ny, nz];
520 for c in cells.iter() {
521 let _ = yee_check_cfl(dt_s, spacing_m, c.epsilon_relative, c.mu_relative)?;
522 }
523
524 for z in 0..nz {
526 let zp = (z + 1) % nz;
527 for y in 0..ny {
528 let yp = (y + 1) % ny;
529 for x in 0..nx {
530 let xp = (x + 1) % nx;
531 let idx = cell_idx(x, y, z, d3);
532 let e = cells[idx].electric_field_v_per_m;
533 let ex_p = cells[cell_idx(xp, y, z, d3)].electric_field_v_per_m;
534 let ey_p = cells[cell_idx(x, yp, z, d3)].electric_field_v_per_m;
535 let ez_p = cells[cell_idx(x, y, zp, d3)].electric_field_v_per_m;
536 let curl_x = (ey_p[2] - e[2]) / spacing_m[1] - (ez_p[1] - e[1]) / spacing_m[2];
537 let curl_y = (ez_p[0] - e[0]) / spacing_m[2] - (ex_p[2] - e[2]) / spacing_m[0];
538 let curl_z = (ex_p[1] - e[1]) / spacing_m[0] - (ey_p[0] - e[0]) / spacing_m[1];
539 let coeff = dt_s / (VACUUM_PERMEABILITY_H_PER_M * cells[idx].mu_relative);
540 cells[idx].magnetic_field_h_a_per_m[0] -= coeff * curl_x;
541 cells[idx].magnetic_field_h_a_per_m[1] -= coeff * curl_y;
542 cells[idx].magnetic_field_h_a_per_m[2] -= coeff * curl_z;
543 }
544 }
545 }
546
547 for z in 0..nz {
549 let zm = (z + nz - 1) % nz;
550 for y in 0..ny {
551 let ym = (y + ny - 1) % ny;
552 for x in 0..nx {
553 let xm = (x + nx - 1) % nx;
554 let idx = cell_idx(x, y, z, d3);
555 let h = cells[idx].magnetic_field_h_a_per_m;
556 let hx_m = cells[cell_idx(xm, y, z, d3)].magnetic_field_h_a_per_m;
557 let hy_m = cells[cell_idx(x, ym, z, d3)].magnetic_field_h_a_per_m;
558 let hz_m = cells[cell_idx(x, y, zm, d3)].magnetic_field_h_a_per_m;
559 let curl_x = (h[2] - hy_m[2]) / spacing_m[1] - (h[1] - hz_m[1]) / spacing_m[2];
560 let curl_y = (h[0] - hz_m[0]) / spacing_m[2] - (h[2] - hx_m[2]) / spacing_m[0];
561 let curl_z = (h[1] - hx_m[1]) / spacing_m[0] - (h[0] - hy_m[0]) / spacing_m[1];
562 let eps = VACUUM_PERMITTIVITY_F_PER_M * cells[idx].epsilon_relative;
563 let sigma = cells[idx].conductivity_s_per_m;
564 let j = cells[idx].impressed_current_j_a_per_m2;
565 let loss = sigma * dt_s / (2.0 * eps);
566 let ca = (1.0 - loss) / (1.0 + loss);
567 let cb = (dt_s / eps) / (1.0 + loss);
568 let e_prev = cells[idx].electric_field_v_per_m;
569 cells[idx].electric_field_v_per_m = [
570 ca * e_prev[0] + cb * (curl_x - j[0]),
571 ca * e_prev[1] + cb * (curl_y - j[1]),
572 ca * e_prev[2] + cb * (curl_z - j[2]),
573 ];
574 }
575 }
576 }
577 Ok(())
578}
579
580pub fn yee_total_energy_j(cells: &[YeeRecord], spacing_m: [f64; 3]) -> Result<f64, Error> {
582 if spacing_m.iter().any(|v| !v.is_finite() || *v <= 0.0) {
583 return Err(Error::Value);
584 }
585 let vol = spacing_m[0] * spacing_m[1] * spacing_m[2];
586 let mut sum = 0.0f64;
587 for c in cells {
588 sum += vol
589 * energy_density_isotropic(
590 c.electric_field_v_per_m,
591 c.magnetic_field_h_a_per_m,
592 c.epsilon_relative,
593 c.mu_relative,
594 )?;
595 }
596 Ok(sum)
597}