Skip to main content

lib_jsl_electromagnetics/propagation/
multipath.rs

1//! Multipath propagation: the two-ray ground reflection model, Fresnel reflection, Fresnel zones
2//! and tapped-delay-line channels.
3//!
4//! See the book entry [Propagation](https://jwkunz.github.io/lib_jsl/book/em-waves/propagation.html).
5
6use crate::conventions::C64;
7use lib_jsl_core::ErrorsJSL;
8use lib_jsl_core::constants::em::C0;
9use std::f64::consts::{PI, TAU};
10
11/// The polarization of a wave reflecting from a plane boundary.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum ReflectionPolarization {
14    /// Electric field perpendicular to the plane of incidence (TE, "horizontal" over ground).
15    Perpendicular,
16    /// Electric field in the plane of incidence (TM, "vertical" over ground).
17    Parallel,
18}
19
20/// The Fresnel reflection coefficient from vacuum onto a half-space of complex relative
21/// permittivity `epsilon` (`ε' − jε''`, engineering convention) at grazing angle `psi` (radians
22/// above the surface).
23pub fn fresnel_reflection(epsilon: C64, grazing_angle: f64, polarization: ReflectionPolarization) -> C64 {
24    let (s, c) = grazing_angle.sin_cos();
25    let root = (epsilon - c * c).sqrt();
26    match polarization {
27        ReflectionPolarization::Perpendicular => (s - root) / (s + root),
28        ReflectionPolarization::Parallel => (epsilon * s - root) / (epsilon * s + root),
29    }
30}
31
32/// Ground conductivity and permittivity as a complex relative permittivity `ε_r − j σ/(ωε₀)`.
33pub fn ground_permittivity(relative_permittivity: f64, conductivity: f64, frequency: f64) -> C64 {
34    C64::new(relative_permittivity, -conductivity / (TAU * frequency * lib_jsl_core::constants::em::EPS_0))
35}
36
37/// The two-ray model: the field of the direct ray plus the ground-reflected ray between antennas
38/// at heights `ht`, `hr` (m) a ground distance `d` apart, relative to the direct ray alone in free
39/// space: `1 + Γ (r₁/r₂) e^{−jk(r₂ − r₁)}`. The received power is the free-space power times
40/// `|factor|²`. With `reflection = None`, a perfect reflector `Γ = −1` is assumed; otherwise the
41/// Fresnel coefficient of the given ground is used.
42pub fn two_ray_factor(distance: f64, ht: f64, hr: f64, frequency: f64, ground: Option<(C64, ReflectionPolarization)>) -> Result<C64, ErrorsJSL> {
43    if !(distance > 0.0) || ht < 0.0 || hr < 0.0 || !(frequency > 0.0) {
44        return Err(ErrorsJSL::InvalidInputRange("Need a positive distance and frequency and non-negative heights."));
45    }
46    // ANCHOR: two_ray
47    let r1 = (distance * distance + (ht - hr).powi(2)).sqrt();
48    let r2 = (distance * distance + (ht + hr).powi(2)).sqrt();
49    let grazing = ((ht + hr) / distance).atan();
50    let gamma = match ground {
51        None => C64::new(-1.0, 0.0),
52        Some((eps, pol)) => fresnel_reflection(eps, grazing, pol),
53    };
54    let k = TAU * frequency / C0;
55    Ok(1.0 + gamma * (r1 / r2) * C64::from_polar(1.0, -k * (r2 - r1)))
56    // ANCHOR_END: two_ray
57}
58
59/// The large-distance two-ray approximation of the received power,
60/// `P_t G_t G_r h_t² h_r² / d⁴` (independent of frequency).
61pub fn two_ray_asymptotic_power(transmit_power: f64, gt: f64, gr: f64, ht: f64, hr: f64, distance: f64) -> f64 {
62    transmit_power * gt * gr * (ht * hr).powi(2) / distance.powi(4)
63}
64
65/// The crossover distance `4π h_t h_r / λ` beyond which the two-ray power falls as `d⁻⁴`.
66pub fn two_ray_crossover_distance(ht: f64, hr: f64, frequency: f64) -> f64 {
67    4.0 * PI * ht * hr * frequency / C0
68}
69
70/// The radius of the `n`-th Fresnel zone at distances `d1`, `d2` from the two ends:
71/// `√(n λ d₁ d₂ / (d₁ + d₂))`.
72pub fn fresnel_zone_radius(n: u32, d1: f64, d2: f64, frequency: f64) -> f64 {
73    (n as f64 * C0 / frequency * d1 * d2 / (d1 + d2)).sqrt()
74}
75
76/// A tapped-delay-line multipath channel `h(t) = Σ a_i δ(t − τ_i)`.
77#[derive(Debug, Clone, PartialEq)]
78pub struct MultipathChannel {
79    /// Path delays (s).
80    pub delays: Vec<f64>,
81    /// Complex path amplitudes.
82    pub gains: Vec<C64>,
83}
84
85impl MultipathChannel {
86    pub fn new(delays: Vec<f64>, gains: Vec<C64>) -> Result<Self, ErrorsJSL> {
87        if delays.is_empty() || delays.len() != gains.len() {
88            return Err(ErrorsJSL::IncompatibleArraySizes((delays.len(), gains.len())));
89        }
90        Ok(MultipathChannel { delays, gains })
91    }
92
93    /// The frequency response `H(f) = Σ a_i e^{−j2πfτ_i}`.
94    pub fn frequency_response(&self, frequency: f64) -> C64 {
95        self.delays.iter().zip(&self.gains).map(|(&t, &a)| a * C64::from_polar(1.0, -TAU * frequency * t)).sum()
96    }
97
98    /// The power-weighted mean delay and the RMS delay spread (s).
99    pub fn delay_statistics(&self) -> (f64, f64) {
100        let p: Vec<f64> = self.gains.iter().map(|g| g.norm_sqr()).collect();
101        let total: f64 = p.iter().sum();
102        let mean = self.delays.iter().zip(&p).map(|(t, w)| t * w).sum::<f64>() / total;
103        let second = self.delays.iter().zip(&p).map(|(t, w)| t * t * w).sum::<f64>() / total;
104        (mean, (second - mean * mean).max(0.0).sqrt())
105    }
106
107    /// The 50% coherence bandwidth estimate `1 / (5 σ_τ)` (Hz).
108    pub fn coherence_bandwidth(&self) -> f64 {
109        1.0 / (5.0 * self.delay_statistics().1)
110    }
111
112    /// Filters complex baseband samples at rate `fs` through the channel (delays rounded to the
113    /// nearest sample).
114    pub fn apply(&self, x: &[C64], fs: f64) -> Vec<C64> {
115        let mut y = vec![C64::new(0.0, 0.0); x.len()];
116        for (&t, &a) in self.delays.iter().zip(&self.gains) {
117            let shift = (t * fs).round() as usize;
118            for n in shift..x.len() {
119                y[n] += a * x[n - shift];
120            }
121        }
122        y
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn fresnel_coefficients_have_the_textbook_limits() {
132        let eps = C64::new(4.0, 0.0);
133        // Normal incidence: (1 − √ε)/(1 + √ε) = −1/3 for perpendicular, +1/3 for parallel.
134        let normal = std::f64::consts::FRAC_PI_2;
135        assert!((fresnel_reflection(eps, normal, ReflectionPolarization::Perpendicular) - C64::new(-1.0 / 3.0, 0.0)).norm() < 1e-12);
136        assert!((fresnel_reflection(eps, normal, ReflectionPolarization::Parallel) - C64::new(1.0 / 3.0, 0.0)).norm() < 1e-12);
137        // Brewster: the parallel coefficient vanishes at grazing angle atan(1/√ε) from the surface normal complement.
138        let brewster_grazing = std::f64::consts::FRAC_PI_2 - 2f64.atan();
139        assert!(fresnel_reflection(eps, brewster_grazing, ReflectionPolarization::Parallel).norm() < 1e-12);
140        // Grazing incidence reflects totally with a phase reversal.
141        assert!((fresnel_reflection(eps, 1e-9, ReflectionPolarization::Perpendicular) + 1.0).norm() < 1e-8);
142        let soil = ground_permittivity(15.0, 0.005, 1e8);
143        assert!(soil.im < 0.0 && (soil.im + 0.005 / (TAU * 1e8 * lib_jsl_core::constants::em::EPS_0)).abs() < 1e-12);
144    }
145
146    #[test]
147    fn two_ray_model_reaches_the_fourth_power_law() {
148        let (ht, hr, f) = (30.0, 2.0, 900e6);
149        let crossover = two_ray_crossover_distance(ht, hr, f);
150        assert!((crossover - 4.0 * PI * 60.0 / (C0 / f)).abs() < 1e-9);
151        let d = 50.0 * crossover;
152        let factor = two_ray_factor(d, ht, hr, f, None).unwrap().norm_sqr();
153        let free = crate::propagation::path_loss::friis_received_power(1.0, 1.0, 1.0, f, d).unwrap();
154        let asymptotic = two_ray_asymptotic_power(1.0, 1.0, 1.0, ht, hr, d);
155        assert!((free * factor / asymptotic - 1.0).abs() < 0.01, "{}", free * factor / asymptotic);
156        // Near the antennas the two rays interfere: nulls dip far below free space.
157        let dips = (100..2000).map(|i| two_ray_factor(i as f64, ht, hr, f, None).unwrap().norm()).fold(f64::INFINITY, f64::min);
158        assert!(dips < 0.05);
159        let ground = Some((ground_permittivity(15.0, 0.005, f), ReflectionPolarization::Parallel));
160        assert!(two_ray_factor(1000.0, ht, hr, f, ground).unwrap().norm() > 0.0);
161        assert!((fresnel_zone_radius(1, 5000.0, 5000.0, 3e9) - (C0 / 3e9 * 2500.0).sqrt()).abs() < 1e-9);
162    }
163
164    #[test]
165    fn delay_spread_and_channel_filtering() {
166        // Two equal paths 1 µs apart: mean 0.5 µs, spread 0.5 µs, notches every 1 MHz.
167        let ch = MultipathChannel::new(vec![0.0, 1e-6], vec![C64::new(1.0, 0.0), C64::new(1.0, 0.0)]).unwrap();
168        let (mean, spread) = ch.delay_statistics();
169        assert!((mean - 0.5e-6).abs() < 1e-18 && (spread - 0.5e-6).abs() < 1e-18);
170        assert!(ch.frequency_response(0.5e6).norm() < 1e-9 && (ch.frequency_response(1e6).norm() - 2.0).abs() < 1e-9);
171        assert!((ch.coherence_bandwidth() - 400e3).abs() < 1e-6);
172        let y = ch.apply(&[C64::new(1.0, 0.0), C64::new(0.0, 0.0), C64::new(0.0, 0.0)], 2e6);
173        assert_eq!(y, vec![C64::new(1.0, 0.0), C64::new(0.0, 0.0), C64::new(1.0, 0.0)]);
174        assert!(MultipathChannel::new(vec![0.0], vec![]).is_err());
175    }
176}