Skip to main content

lib_jsl_electromagnetics/fields/
physics.rs

1//! Physical operations on fields, with quantity checks: plane waves, the Poynting vector, power
2//! flow, far-field radiation intensity and directivity, fields from potentials, wave impedance.
3//!
4//! See the book entry [Fields on grids](https://jwkunz.github.io/lib_jsl/book/em-arrays/fields.html).
5
6use crate::conventions::{C64, Medium};
7use crate::coordinates::polarization::PolarizationBasis;
8use crate::coordinates::systems::CoordinateSystem;
9use crate::fields::domain::{Domain, DomainKind};
10use crate::fields::field_container::{FieldQuantity, HarmonicField, Rank, TimeField};
11use lib_jsl_core::ErrorsJSL;
12use ndarray::{Array2, Array3};
13use std::f64::consts::PI;
14use std::sync::Arc;
15
16fn expect(field_quantity: FieldQuantity, wanted: FieldQuantity, what: &'static str) -> Result<(), ErrorsJSL> {
17    if field_quantity != wanted {
18        return Err(ErrorsJSL::InvalidInputRange(what));
19    }
20    Ok(())
21}
22
23fn cross(a: [C64; 3], b: [C64; 3]) -> [C64; 3] {
24    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
25}
26
27fn cartesian_field(domain: Arc<Domain>, quantity: FieldQuantity, template: &HarmonicField, values: Vec<[C64; 3]>) -> Result<HarmonicField, ErrorsJSL> {
28    let arr = Array2::from_shape_fn((domain.len(), 3), |(i, k)| values[i][k]);
29    HarmonicField::new(domain, quantity, Rank::Vector(PolarizationBasis::CARTESIAN), template.frequency(), template.convention(), arr)
30}
31
32/// A uniform plane wave `E = E₀ p̂ e^{-jk k̂·r}` and `H = k̂ × E / η` on a (non-far-field) domain,
33/// both in Cartesian components. `direction` is the propagation direction (normalised here) and
34/// `polarization` the Cartesian electric polarization (its component along `direction` is
35/// removed, then it is normalised).
36pub fn plane_wave(domain: Arc<Domain>, direction: [f64; 3], polarization: [C64; 3], amplitude: C64, frequency: f64, medium: &Medium, convention: crate::conventions::TimeConvention) -> Result<(HarmonicField, HarmonicField), ErrorsJSL> {
37    if domain.is_far_field() {
38        return Err(ErrorsJSL::InvalidInputRange("Plane waves are defined on spatial domains, not the far-field sphere."));
39    }
40    let n = (direction[0] * direction[0] + direction[1] * direction[1] + direction[2] * direction[2]).sqrt();
41    if n == 0.0 {
42        return Err(ErrorsJSL::InvalidInputRange("The propagation direction must be non-zero."));
43    }
44    let k_hat = direction.map(|v| v / n);
45    let along: C64 = (0..3).map(|i| polarization[i] * k_hat[i]).sum();
46    let p: [C64; 3] = std::array::from_fn(|i| polarization[i] - along * k_hat[i]);
47    let pn = p.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt();
48    if pn == 0.0 {
49        return Err(ErrorsJSL::InvalidInputRange("The polarization must have a component transverse to the direction."));
50    }
51    let p = p.map(|v| v / pn);
52    let k = medium.wavenumber(frequency, convention);
53    let eta = medium.impedance(convention);
54    let k_c = k_hat.map(|v| C64::new(v, 0.0));
55    let e = HarmonicField::vector_from_fn(domain.clone(), FieldQuantity::ElectricField, PolarizationBasis::CARTESIAN, frequency, convention, |pos| {
56        let r = pos.to_cartesian();
57        let phase = (-convention.unit() * k * (k_hat[0] * r[0] + k_hat[1] * r[1] + k_hat[2] * r[2])).exp();
58        p.map(|v| v * amplitude * phase)
59    })?;
60    let h_values: Vec<[C64; 3]> = (0..e.len()).map(|i| cross(k_c, e.vector(i)).map(|v| v / eta)).collect();
61    let h = cartesian_field(domain, FieldQuantity::MagneticField, &e, h_values)?;
62    Ok((e, h))
63}
64
65/// The complex Poynting vector `S = ½ E × H*` (its real part is the time-averaged power density),
66/// in Cartesian components. Requires an electric and a magnetic field on the same domain.
67pub fn poynting(e: &HarmonicField, h: &HarmonicField) -> Result<HarmonicField, ErrorsJSL> {
68    expect(e.quantity(), FieldQuantity::ElectricField, "The first field must be the electric field E.")?;
69    expect(h.quantity(), FieldQuantity::MagneticField, "The second field must be the magnetic field H.")?;
70    if !(Arc::ptr_eq(e.domain(), h.domain()) || e.domain() == h.domain()) || e.convention() != h.convention() || e.is_scalar() || h.is_scalar() {
71        return Err(ErrorsJSL::InvalidInputRange("E and H must be vector fields on the same domain and convention."));
72    }
73    let s: Vec<[C64; 3]> = (0..e.len()).map(|i| cross(e.cartesian(i), h.cartesian(i).map(|v| v.conj())).map(|v| v * 0.5)).collect();
74    cartesian_field(e.domain().clone(), FieldQuantity::PowerDensity, e, s)
75}
76
77/// The outward unit normal of a surface domain at a sample (`+ẑ`, `r̂` or `ρ̂`).
78fn surface_normal(domain: &Domain, sample: usize) -> Result<[f64; 3], ErrorsJSL> {
79    let p = domain.position_flat(sample);
80    match domain.kind() {
81        DomainKind::Plane { .. } => Ok([0.0, 0.0, 1.0]),
82        DomainKind::Sphere { .. } => Ok(p.frame(CoordinateSystem::Spherical)[0]),
83        DomainKind::Cylinder { .. } => Ok(p.frame(CoordinateSystem::Cylindrical)[0]),
84        _ => Err(ErrorsJSL::InvalidInputRange("Power flow needs a plane, sphere or cylinder surface.")),
85    }
86}
87
88/// The time-averaged power `∫ Re(S)·n̂ dA` through a surface (normal `+ẑ` for planes, outward for
89/// spheres and cylinders).
90pub fn power_through_surface(e: &HarmonicField, h: &HarmonicField) -> Result<f64, ErrorsJSL> {
91    let s = poynting(e, h)?;
92    let d = s.domain();
93    (0..d.len())
94        .map(|i| {
95            let n = surface_normal(d, i)?;
96            let v = s.vector(i);
97            Ok(d.weights()[i] * (0..3).map(|k| v[k].re * n[k]).sum::<f64>())
98        })
99        .sum()
100}
101
102/// The instantaneous Poynting vector `S(t) = E(t) × H(t)` of time-domain fields.
103pub fn poynting_time(e: &TimeField, h: &TimeField) -> Result<TimeField, ErrorsJSL> {
104    expect(e.quantity(), FieldQuantity::ElectricField, "The first field must be the electric field E.")?;
105    expect(h.quantity(), FieldQuantity::MagneticField, "The second field must be the magnetic field H.")?;
106    let (Rank::Vector(be), Rank::Vector(bh)) = (e.rank(), h.rank()) else {
107        return Err(ErrorsJSL::InvalidInputRange("E and H must be vector fields."));
108    };
109    if !(Arc::ptr_eq(e.domain(), h.domain()) || e.domain() == h.domain()) || e.time_axis() != h.time_axis() {
110        return Err(ErrorsJSL::InvalidInputRange("E and H must share a domain and time axis."));
111    }
112    let (steps, n, _) = e.values().dim();
113    let mut out = Array3::<f64>::zeros((steps, n, 3));
114    for i in 0..n {
115        let p = e.domain().position_flat(i);
116        for t in 0..steps {
117            let ev = be.convert_real([e.values()[[t, i, 0]], e.values()[[t, i, 1]], e.values()[[t, i, 2]]], PolarizationBasis::CARTESIAN, &p)?;
118            let hv = bh.convert_real([h.values()[[t, i, 0]], h.values()[[t, i, 1]], h.values()[[t, i, 2]]], PolarizationBasis::CARTESIAN, &p)?;
119            let s = [ev[1] * hv[2] - ev[2] * hv[1], ev[2] * hv[0] - ev[0] * hv[2], ev[0] * hv[1] - ev[1] * hv[0]];
120            for k in 0..3 {
121                out[[t, i, k]] = s[k];
122            }
123        }
124    }
125    TimeField::new(e.domain().clone(), FieldQuantity::PowerDensity, Rank::Vector(PolarizationBasis::CARTESIAN), e.time_axis(), out)
126}
127
128fn require_far_field(e: &HarmonicField) -> Result<(), ErrorsJSL> {
129    expect(e.quantity(), FieldQuantity::ElectricField, "Far-field operations need the electric field E.")?;
130    if !e.domain().is_far_field() || e.is_scalar() {
131        return Err(ErrorsJSL::InvalidInputRange("Far-field operations need an E field on the far-field sphere."));
132    }
133    Ok(())
134}
135
136/// The radiation intensity `U = |E_ff|² / (2η)` (W/sr) of a far-field pattern `E_ff = r e^{jkr} E`.
137pub fn radiation_intensity(e: &HarmonicField, medium: &Medium) -> Result<HarmonicField, ErrorsJSL> {
138    require_far_field(e)?;
139    let eta = medium.impedance(e.convention()).re;
140    let intensity = e.norm_squared();
141    let values = Array2::from_shape_fn((e.len(), 1), |(i, _)| C64::new(intensity[i] / (2.0 * eta), 0.0));
142    HarmonicField::new(e.domain().clone(), FieldQuantity::Generic, Rank::Scalar, e.frequency(), e.convention(), values)
143}
144
145/// The total radiated power `∫ U dΩ` of a far-field pattern.
146pub fn radiated_power(e: &HarmonicField, medium: &Medium) -> Result<f64, ErrorsJSL> {
147    Ok(radiation_intensity(e, medium)?.integrate()?.re)
148}
149
150/// The directivity pattern `D(Ω) = 4π U(Ω) / P_rad` (dimensionless).
151pub fn directivity(e: &HarmonicField) -> Result<HarmonicField, ErrorsJSL> {
152    let u = radiation_intensity(e, &Medium::VACUUM)?;
153    let p = u.integrate()?.re;
154    if p <= 0.0 {
155        return Err(ErrorsJSL::InvalidInputRange("The pattern radiates no power."));
156    }
157    Ok(u.scaled(C64::new(4.0 * PI / p, 0.0)))
158}
159
160/// The largest value of the directivity pattern on its grid.
161pub fn peak_directivity(e: &HarmonicField) -> Result<f64, ErrorsJSL> {
162    Ok(directivity(e)?.values().iter().map(|v| v.re).fold(0.0, f64::max))
163}
164
165/// The fields of the potentials: `E = -∇Φ - ∂A/∂t` (with `∂/∂t → ±jω` per convention) and
166/// `B = ∇ × A`, on a volume domain. Returns `(E, B)` in the domain's linear basis.
167pub fn fields_from_potentials(phi: &HarmonicField, a: &HarmonicField) -> Result<(HarmonicField, HarmonicField), ErrorsJSL> {
168    expect(phi.quantity(), FieldQuantity::ScalarPotential, "The first field must be the scalar potential Φ.")?;
169    expect(a.quantity(), FieldQuantity::VectorPotential, "The second field must be the vector potential A.")?;
170    let grad = phi.gradient()?;
171    let a_native = a.to_basis(grad.basis().expect("gradients are vectors"))?;
172    let dadt = a_native.time_derivative();
173    let mut e = grad.scaled(C64::new(-1.0, 0.0));
174    *e.values_mut() = e.values() - dadt.values();
175    let e = e.with_quantity(FieldQuantity::ElectricField)?;
176    let b = a.curl()?.with_quantity(FieldQuantity::MagneticFluxDensity)?;
177    Ok((e, b))
178}
179
180/// The wave impedance `|E| / |H|` at every sample (Ω); `∞` where `H` vanishes.
181pub fn wave_impedance(e: &HarmonicField, h: &HarmonicField) -> Result<Vec<f64>, ErrorsJSL> {
182    expect(e.quantity(), FieldQuantity::ElectricField, "The first field must be the electric field E.")?;
183    expect(h.quantity(), FieldQuantity::MagneticField, "The second field must be the magnetic field H.")?;
184    if e.len() != h.len() {
185        return Err(ErrorsJSL::IncompatibleArraySizes((e.len(), h.len())));
186    }
187    Ok(e.norm_squared().iter().zip(h.norm_squared()).map(|(a, b)| if b > 0.0 { (a / b).sqrt() } else { f64::INFINITY }).collect())
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use crate::conventions::TimeConvention;
194    use crate::fields::domain::Axis;
195    use crate::fields::field_container::TimeAxis;
196    use std::f64::consts::TAU;
197
198    fn c(re: f64) -> C64 {
199        C64::new(re, 0.0)
200    }
201
202    #[test]
203    fn plane_wave_power_flux_and_impedance() {
204        let f = 3e8;
205        let plane = Arc::new(Domain::plane(Axis::uniform(-0.5, 0.5, 11).unwrap(), Axis::uniform(-1.0, 1.0, 11).unwrap(), 0.3).unwrap());
206        let (e, h) = plane_wave(plane.clone(), [0.0, 0.0, 1.0], [c(1.0), c(0.0), c(0.0)], c(2.0), f, &Medium::VACUUM, TimeConvention::PlusJ).unwrap();
207        let eta = Medium::VACUUM.impedance(TimeConvention::PlusJ).re;
208        let want = 4.0 / (2.0 * eta) * plane.measure(); // |E|²/(2η) × area
209        assert!((power_through_surface(&e, &h).unwrap() - want).abs() < 1e-12 * want);
210        assert!(wave_impedance(&e, &h).unwrap().iter().all(|z| (z - eta).abs() < 1e-9));
211        // Through a closed sphere a plane wave carries no net power, in either convention.
212        let sphere = Arc::new(Domain::sphere(0.4, Axis::gauss_legendre_polar(16).unwrap(), Axis::periodic(0.0, TAU, 32).unwrap()).unwrap());
213        for conv in [TimeConvention::PlusJ, TimeConvention::MinusI] {
214            let (es, hs) = plane_wave(sphere.clone(), [1.0, 1.0, 0.0], [c(0.0), c(0.0), c(1.0)], c(1.0), f, &Medium::VACUUM, conv).unwrap();
215            assert!(power_through_surface(&es, &hs).unwrap().abs() < 1e-12);
216        }
217        // Errors: wrong quantities, far-field domains, bad polarization.
218        assert!(poynting(&h, &e).is_err());
219        assert!(plane_wave(Arc::new(Domain::far_field_gauss(2, 4).unwrap()), [0.0, 0.0, 1.0], [c(1.0), c(0.0), c(0.0)], c(1.0), f, &Medium::VACUUM, TimeConvention::PlusJ).is_err());
220        assert!(plane_wave(plane.clone(), [0.0, 0.0, 1.0], [c(0.0), c(0.0), c(1.0)], c(1.0), f, &Medium::VACUUM, TimeConvention::PlusJ).is_err());
221        assert!(plane_wave(plane, [0.0; 3], [c(1.0), c(0.0), c(0.0)], c(1.0), f, &Medium::VACUUM, TimeConvention::PlusJ).is_err());
222    }
223
224    #[test]
225    fn instantaneous_poynting_averages_to_the_complex_one() {
226        let f = 1e8;
227        let plane = Arc::new(Domain::plane(Axis::uniform(0.0, 1.0, 2).unwrap(), Axis::uniform(0.0, 1.0, 2).unwrap(), 0.0).unwrap());
228        let (e, h) = plane_wave(plane, [0.0, 0.0, 1.0], [c(0.0), c(1.0), c(0.0)], c(3.0), f, &Medium::VACUUM, TimeConvention::PlusJ).unwrap();
229        let t = TimeAxis::new(0.0, 1.0 / (f * 64.0), 64).unwrap();
230        let s_t = poynting_time(&e.to_time_series(t).unwrap(), &h.to_time_series(t).unwrap()).unwrap();
231        let mean: f64 = (0..64).map(|k| s_t.at(k, 0)[2]).sum::<f64>() / 64.0;
232        assert!((mean - poynting(&e, &h).unwrap().vector(0)[2].re).abs() < 1e-12);
233    }
234
235    #[test]
236    fn far_field_intensity_power_and_directivity_of_a_short_dipole() {
237        // An odd node count puts a sample exactly on the equator, where the peak is.
238        let d = Arc::new(Domain::far_field_gauss(13, 24).unwrap());
239        let e = HarmonicField::vector_from_fn(d, FieldQuantity::ElectricField, PolarizationBasis::SPHERICAL, 1e9, TimeConvention::PlusJ, |p| [c(0.0), c(10.0 * p.coords[1].sin()), c(0.0)]).unwrap();
240        let eta = Medium::VACUUM.impedance(TimeConvention::PlusJ).re;
241        // P = ∫ 100 sin²θ / (2η) dΩ = 100 · (8π/3) / (2η).
242        assert!((radiated_power(&e, &Medium::VACUUM).unwrap() - 100.0 * 8.0 * PI / 3.0 / (2.0 * eta)).abs() < 1e-10);
243        assert!((peak_directivity(&e).unwrap() - 1.5).abs() < 1e-10);
244        assert!((directivity(&e).unwrap().integrate().unwrap().re - 4.0 * PI).abs() < 1e-10);
245        let zero = e.scaled(c(0.0));
246        assert!(directivity(&zero).is_err());
247        assert!(radiated_power(&e.clone().with_quantity(FieldQuantity::MagneticField).unwrap(), &Medium::VACUUM).is_err());
248    }
249
250    #[test]
251    fn potentials_give_the_expected_fields() {
252        let axis = || Axis::uniform(-1.0, 1.0, 5).unwrap();
253        let d = Arc::new(Domain::cartesian_box(axis(), axis(), axis()).unwrap());
254        let f = 1e3;
255        let omega = TAU * f;
256        // Φ = 2x, A = B₀/2 (-y, x, 0): E = -2x̂ - jωA, B = B₀ ẑ.
257        let phi = HarmonicField::scalar_from_fn(d.clone(), FieldQuantity::ScalarPotential, f, TimeConvention::PlusJ, |p| c(2.0 * p.coords[0])).unwrap();
258        let b0 = 0.3;
259        let a = HarmonicField::vector_from_fn(d.clone(), FieldQuantity::VectorPotential, PolarizationBasis::CARTESIAN, f, TimeConvention::PlusJ, |p| [c(-b0 / 2.0 * p.coords[1]), c(b0 / 2.0 * p.coords[0]), c(0.0)]).unwrap();
260        let (e, b) = fields_from_potentials(&phi, &a).unwrap();
261        assert_eq!((e.quantity(), b.quantity()), (FieldQuantity::ElectricField, FieldQuantity::MagneticFluxDensity));
262        let i = d.flatten(&[3, 1, 2]);
263        let [x, y, _] = d.position_flat(i).to_cartesian();
264        let ev = e.vector(i);
265        assert!((ev[0] - (c(-2.0) - C64::new(0.0, omega) * (-b0 / 2.0 * y))).norm() < 1e-9);
266        assert!((ev[1] - (-C64::new(0.0, omega) * (b0 / 2.0 * x))).norm() < 1e-9);
267        assert!((b.vector(i)[2] - c(b0)).norm() < 1e-9);
268        assert!(fields_from_potentials(&a, &phi).is_err());
269    }
270}