Skip to main content

lib_jsl_electromagnetics/
conventions.rs

1//! Conventions shared by the whole crate: the harmonic time convention, media, and dB helpers.
2//!
3//! Units are SI. Harmonic quantities are complex peak phasors; time-averaged products carry the
4//! factor ½ (for example `S = ½ E × H*`).
5//!
6//! See the book entry [Fields on grids](https://jwkunz.github.io/lib_jsl/book/em-arrays/fields.html#conventions).
7
8use lib_jsl_core::constants::em::{C0, EPS_0, MU_0};
9use num_complex::Complex;
10use std::f64::consts::TAU;
11
12pub type C64 = Complex<f64>;
13
14/// The sign convention relating a phasor `X` to its real signal.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
16pub enum TimeConvention {
17    /// `x(t) = Re{X e^{+jωt}}` (engineering). Outgoing waves are `e^{-jkr}`, `∂/∂t → +jω`.
18    #[default]
19    PlusJ,
20    /// `x(t) = Re{X e^{-iωt}}` (physics). Outgoing waves are `e^{+ikr}`, `∂/∂t → -iω`.
21    MinusI,
22}
23
24impl TimeConvention {
25    /// `+1` for `e^{+jωt}`, `-1` for `e^{-iωt}`: the sign of `ωt` in the exponent.
26    pub fn sign(self) -> f64 {
27        match self {
28            TimeConvention::PlusJ => 1.0,
29            TimeConvention::MinusI => -1.0,
30        }
31    }
32
33    /// The imaginary unit as it appears in `e^{(this) ωt}`: `+j` or `-i`.
34    pub fn unit(self) -> C64 {
35        C64::new(0.0, self.sign())
36    }
37
38    /// The factor that `∂/∂t` becomes: `+jω` or `-iω`.
39    pub fn time_derivative(self, omega: f64) -> C64 {
40        self.unit() * omega
41    }
42
43    /// The outgoing spherical wave phase `e^{-jkr}` (or `e^{+ikr}`) for a possibly complex `k`.
44    pub fn outgoing(self, k: C64, r: f64) -> C64 {
45        (-self.unit() * k * r).exp()
46    }
47
48    /// Re-expresses a phasor written in this convention in the `other` convention (complex
49    /// conjugation when they differ), so both describe the same real signal.
50    pub fn convert(self, value: C64, other: TimeConvention) -> C64 {
51        if self == other { value } else { value.conj() }
52    }
53
54    /// The real signal of a phasor at time `t`.
55    pub fn instantaneous(self, phasor: C64, omega: f64, t: f64) -> f64 {
56        (phasor * C64::from_polar(1.0, self.sign() * omega * t)).re
57    }
58}
59
60/// A linear, homogeneous, isotropic medium described by complex relative permittivity and
61/// permeability. Losses are given in the [`TimeConvention::PlusJ`] form (`ε_r = ε' - jε''` with
62/// `ε'' >= 0`); the medium's methods convert to the requested convention.
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct Medium {
65    pub eps_r: C64,
66    pub mu_r: C64,
67}
68
69impl Default for Medium {
70    fn default() -> Self {
71        Medium::VACUUM
72    }
73}
74
75impl Medium {
76    pub const VACUUM: Medium = Medium { eps_r: C64 { re: 1.0, im: 0.0 }, mu_r: C64 { re: 1.0, im: 0.0 } };
77
78    /// A lossless dielectric with relative permittivity `eps_r`.
79    pub fn dielectric(eps_r: f64) -> Self {
80        Medium { eps_r: C64::new(eps_r, 0.0), mu_r: C64::new(1.0, 0.0) }
81    }
82
83    /// A lossy dielectric from relative permittivity and loss tangent `tan δ`.
84    pub fn lossy_dielectric(eps_r: f64, loss_tangent: f64) -> Self {
85        Medium { eps_r: C64::new(eps_r, -eps_r * loss_tangent), mu_r: C64::new(1.0, 0.0) }
86    }
87
88    /// A conductor-like medium: relative permittivity plus conductivity `σ` at `frequency`.
89    pub fn with_conductivity(eps_r: f64, sigma: f64, frequency: f64) -> Self {
90        Medium { eps_r: C64::new(eps_r, -sigma / (TAU * frequency * EPS_0)), mu_r: C64::new(1.0, 0.0) }
91    }
92
93    fn in_convention(&self, convention: TimeConvention) -> (C64, C64) {
94        (TimeConvention::PlusJ.convert(self.eps_r, convention), TimeConvention::PlusJ.convert(self.mu_r, convention))
95    }
96
97    /// The wavenumber `k = ω √(μ ε)` at `frequency`, on the branch for which outgoing waves decay
98    /// (`Im k <= 0` for `e^{+jωt}`, `Im k >= 0` for `e^{-iωt}`), with `Re k >= 0`.
99    pub fn wavenumber(&self, frequency: f64, convention: TimeConvention) -> C64 {
100        let (eps, mu) = self.in_convention(convention);
101        let mut k = (eps * mu).sqrt() * (TAU * frequency / C0);
102        if k.re < 0.0 {
103            k = -k;
104        }
105        k
106    }
107
108    /// The intrinsic impedance `η = √(μ/ε)` (`≈ 376.73 Ω` in vacuum), with `Re η >= 0`.
109    pub fn impedance(&self, convention: TimeConvention) -> C64 {
110        let (eps, mu) = self.in_convention(convention);
111        let mut z = (mu * MU_0 / (eps * EPS_0)).sqrt();
112        if z.re < 0.0 {
113            z = -z;
114        }
115        z
116    }
117
118    /// The wavelength `2π / Re k`.
119    pub fn wavelength(&self, frequency: f64) -> f64 {
120        TAU / self.wavenumber(frequency, TimeConvention::PlusJ).re
121    }
122
123    /// The phase velocity `ω / Re k`.
124    pub fn phase_velocity(&self, frequency: f64) -> f64 {
125        TAU * frequency / self.wavenumber(frequency, TimeConvention::PlusJ).re
126    }
127}
128
129/// A power ratio in decibels.
130pub fn power_to_db(ratio: f64) -> f64 {
131    10.0 * ratio.log10()
132}
133
134/// Decibels to a power ratio.
135pub fn db_to_power(db: f64) -> f64 {
136    10f64.powf(db / 10.0)
137}
138
139/// A field (amplitude) ratio in decibels.
140pub fn amplitude_to_db(ratio: f64) -> f64 {
141    20.0 * ratio.log10()
142}
143
144/// Decibels to an amplitude ratio.
145pub fn db_to_amplitude(db: f64) -> f64 {
146    10f64.powf(db / 20.0)
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn conventions_describe_the_same_real_signal() {
155        let x = C64::from_polar(2.0, 0.7);
156        let omega = 3.0;
157        for t in [0.0, 0.1, 0.37, 1.9] {
158            let a = TimeConvention::PlusJ.instantaneous(x, omega, t);
159            let b = TimeConvention::MinusI.instantaneous(TimeConvention::PlusJ.convert(x, TimeConvention::MinusI), omega, t);
160            assert!((a - b).abs() < 1e-12);
161            assert!((a - 2.0 * (omega * t + 0.7).cos()).abs() < 1e-12);
162        }
163        assert_eq!(TimeConvention::default(), TimeConvention::PlusJ);
164        assert_eq!(TimeConvention::PlusJ.convert(x, TimeConvention::PlusJ), x);
165        // d/dt of Re{X e^{sjωt}} equals Re{(sjω) X e^{sjωt}} in both conventions.
166        for conv in [TimeConvention::PlusJ, TimeConvention::MinusI] {
167            let (t, h) = (0.4, 1e-6);
168            let numeric = (conv.instantaneous(x, omega, t + h) - conv.instantaneous(x, omega, t - h)) / (2.0 * h);
169            assert!((numeric - conv.instantaneous(conv.time_derivative(omega) * x, omega, t)).abs() < 1e-6);
170        }
171    }
172
173    #[test]
174    fn vacuum_and_lossy_media() {
175        let f = 1e9;
176        let k = Medium::VACUUM.wavenumber(f, TimeConvention::PlusJ);
177        assert!((k.re - TAU * f / C0).abs() < 1e-9 && k.im == 0.0);
178        assert!((Medium::VACUUM.impedance(TimeConvention::PlusJ).re - 376.730_313).abs() < 1e-3);
179        assert!((Medium::VACUUM.wavelength(f) - C0 / f).abs() < 1e-12);
180        let glass = Medium::dielectric(4.0);
181        assert!((glass.wavelength(f) - C0 / f / 2.0).abs() < 1e-12 && (glass.phase_velocity(f) - C0 / 2.0).abs() < 1e-3);
182        // A lossy medium attenuates outgoing waves in either convention.
183        let lossy = Medium::lossy_dielectric(4.0, 0.1);
184        for conv in [TimeConvention::PlusJ, TimeConvention::MinusI] {
185            let kc = lossy.wavenumber(f, conv);
186            assert!(kc.re > 0.0);
187            assert!(conv.outgoing(kc, 2.0).norm() < conv.outgoing(kc, 1.0).norm(), "{conv:?}");
188            assert!((conv.outgoing(k, 3.0).norm() - 1.0).abs() < 1e-12);
189        }
190        assert!(Medium::with_conductivity(1.0, 5.8e7, 1e6).eps_r.im < -1e10);
191    }
192
193    #[test]
194    fn decibels() {
195        assert!((power_to_db(100.0) - 20.0).abs() < 1e-12 && (db_to_power(3.0) - 1.995_262_314_968_88).abs() < 1e-12);
196        assert!((amplitude_to_db(10.0) - 20.0).abs() < 1e-12 && (db_to_amplitude(-6.0) - 0.501_187_233_627_272_3).abs() < 1e-12);
197    }
198}