Skip to main content

lib_jsl_electromagnetics/networks/
transmission_lines.rs

1//! Transmission lines: impedance transformation, reflection, standing waves and matching.
2//!
3//! Phasors use the engineering convention `e^{+jωt}`: a wave travelling towards the load is
4//! `e^{−γz}` with propagation constant `γ = α + jβ`, and lines are characterised per unit length
5//! by `R, L, G, C`, giving `Z₀ = √((R + jωL)/(G + jωC))` and `γ = √((R + jωL)(G + jωC))`.
6//!
7//! See the book entry [Transmission lines, two-port networks and the Smith chart](https://jwkunz.github.io/lib_jsl/book/em-waves/transmission-lines.html).
8
9use crate::conventions::C64;
10use lib_jsl_core::ErrorsJSL;
11use lib_jsl_core::constants::em::C0;
12use std::f64::consts::{PI, TAU};
13
14/// A uniform transmission line.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub enum TransmissionLine {
17    /// A lossless line of real characteristic impedance with phase velocity `v = factor · c`.
18    Lossless { impedance: f64, velocity_factor: f64 },
19    /// A line with per-unit-length resistance (Ω/m), inductance (H/m), conductance (S/m) and
20    /// capacitance (F/m).
21    Distributed { r: f64, l: f64, g: f64, c: f64 },
22}
23
24impl TransmissionLine {
25    pub fn lossless(impedance: f64, velocity_factor: f64) -> Result<Self, ErrorsJSL> {
26        if !(impedance > 0.0) || !(velocity_factor > 0.0 && velocity_factor <= 1.0) {
27            return Err(ErrorsJSL::InvalidInputRange("Need a positive impedance and 0 < velocity factor <= 1."));
28        }
29        Ok(TransmissionLine::Lossless { impedance, velocity_factor })
30    }
31
32    pub fn distributed(r: f64, l: f64, g: f64, c: f64) -> Result<Self, ErrorsJSL> {
33        if r < 0.0 || g < 0.0 || !(l > 0.0) || !(c > 0.0) {
34            return Err(ErrorsJSL::InvalidInputRange("Need R, G >= 0 and L, C > 0."));
35        }
36        Ok(TransmissionLine::Distributed { r, l, g, c })
37    }
38
39    /// The characteristic impedance `Z₀` at `frequency`.
40    pub fn characteristic_impedance(&self, frequency: f64) -> C64 {
41        match *self {
42            TransmissionLine::Lossless { impedance, .. } => C64::new(impedance, 0.0),
43            TransmissionLine::Distributed { r, l, g, c } => {
44                let w = TAU * frequency;
45                (C64::new(r, w * l) / C64::new(g, w * c)).sqrt()
46            }
47        }
48    }
49
50    /// The propagation constant `γ = α + jβ` (Np/m, rad/m).
51    pub fn propagation_constant(&self, frequency: f64) -> C64 {
52        match *self {
53            TransmissionLine::Lossless { velocity_factor, .. } => C64::new(0.0, TAU * frequency / (velocity_factor * C0)),
54            TransmissionLine::Distributed { r, l, g, c } => {
55                let w = TAU * frequency;
56                let gamma = (C64::new(r, w * l) * C64::new(g, w * c)).sqrt();
57                if gamma.re < 0.0 { -gamma } else { gamma }
58            }
59        }
60    }
61
62    /// The guided wavelength `2π/β`.
63    pub fn wavelength(&self, frequency: f64) -> f64 {
64        TAU / self.propagation_constant(frequency).im
65    }
66
67    /// The impedance seen at the input of a section of `length` metres terminated in `load`
68    /// (`Z_in = Z₀ (Z_L + Z₀ tanh γl) / (Z₀ + Z_L tanh γl)`; an infinite load is an open circuit).
69    pub fn input_impedance(&self, load: C64, length: f64, frequency: f64) -> C64 {
70        // ANCHOR: input_impedance
71        // The cosh/sinh form avoids the poles of tanh at odd multiples of a quarter wave.
72        let z0 = self.characteristic_impedance(frequency);
73        let gl = self.propagation_constant(frequency) * length;
74        let (ch, sh) = (gl.cosh(), gl.sinh());
75        if load.re.is_infinite() || load.im.is_infinite() {
76            return z0 * ch / sh;
77        }
78        z0 * (load * ch + z0 * sh) / (z0 * ch + load * sh)
79        // ANCHOR_END: input_impedance
80    }
81
82    /// The ABCD (chain) matrix of a section: `[[cosh γl, Z₀ sinh γl], [sinh γl / Z₀, cosh γl]]`.
83    pub fn abcd(&self, length: f64, frequency: f64) -> [[C64; 2]; 2] {
84        let z0 = self.characteristic_impedance(frequency);
85        let gl = self.propagation_constant(frequency) * length;
86        [[gl.cosh(), z0 * gl.sinh()], [gl.sinh() / z0, gl.cosh()]]
87    }
88
89    /// `|V(d)| / |V⁺|` at distances `d` from the load: `|e^{γd} + Γ_L e^{−γd}|`, the
90    /// standing-wave envelope.
91    pub fn standing_wave(&self, load: C64, distances: &[f64], frequency: f64) -> Vec<f64> {
92        let gamma_l = reflection_coefficient(load, self.characteristic_impedance(frequency));
93        let g = self.propagation_constant(frequency);
94        distances.iter().map(|&d| ((g * d).exp() + gamma_l * (-g * d).exp()).norm()).collect()
95    }
96}
97
98/// The reflection coefficient `Γ = (Z − Z₀)/(Z + Z₀)` (`1` for an open circuit).
99pub fn reflection_coefficient(load: C64, z0: C64) -> C64 {
100    if load.re.is_infinite() || load.im.is_infinite() {
101        return C64::new(1.0, 0.0);
102    }
103    (load - z0) / (load + z0)
104}
105
106/// The voltage standing-wave ratio `(1 + |Γ|)/(1 − |Γ|)` (infinite for total reflection).
107pub fn vswr(gamma: C64) -> f64 {
108    let m = gamma.norm();
109    if m >= 1.0 { f64::INFINITY } else { (1.0 + m) / (1.0 - m) }
110}
111
112/// The return loss `−20 log₁₀ |Γ|` in dB.
113pub fn return_loss_db(gamma: C64) -> f64 {
114    -20.0 * gamma.norm().log10()
115}
116
117/// The mismatch loss `−10 log₁₀(1 − |Γ|²)` in dB: the power lost to reflection.
118pub fn mismatch_loss_db(gamma: C64) -> f64 {
119    -10.0 * (1.0 - gamma.norm_sqr()).log10()
120}
121
122/// The characteristic impedance `√(Z_in Z_L)` of a quarter-wave transformer matching real
123/// impedances.
124pub fn quarter_wave_transformer(source: f64, load: f64) -> f64 {
125    (source * load).sqrt()
126}
127
128/// Single shunt short-circuited stub matching of `load` to a lossless line of impedance `z0`:
129/// returns both solutions as `(distance from the load, stub length)`, in wavelengths.
130pub fn single_stub_match(load: C64, z0: f64) -> Result<[(f64, f64); 2], ErrorsJSL> {
131    if load.re <= 0.0 {
132        return Err(ErrorsJSL::InvalidInputRange("Stub matching needs a load with positive resistance."));
133    }
134    let gamma = reflection_coefficient(load, C64::new(z0, 0.0));
135    if gamma.norm() < 1e-12 {
136        return Ok([(0.0, 0.25), (0.0, 0.25)]);
137    }
138    // The normalised admittance y(d) = (1 − Γe^{−j2βd})/(1 + Γe^{−j2βd}) must have real part 1,
139    // i.e. Γe^{−j2βd} on the circle g = 1 of the admittance chart: cos(θ_Γ − 2βd) = −|Γ|.
140    let (m, phase) = (gamma.norm(), gamma.arg());
141    let theta = (-m).acos();
142    let mut out = [(0.0, 0.0); 2];
143    for (k, target) in [theta, -theta].into_iter().enumerate() {
144        // 2βd = phase − target (mod 2π), d in wavelengths: βd = 2π d.
145        let d = ((phase - target).rem_euclid(TAU)) / (4.0 * PI);
146        let rotated = gamma * C64::from_polar(1.0, -4.0 * PI * d);
147        let y = (C64::new(1.0, 0.0) - rotated) / (C64::new(1.0, 0.0) + rotated);
148        // A shorted stub of length s has admittance −j cot(2πs); cancel the susceptance b.
149        let b = y.im;
150        let s = ((1.0 / b).atan() / TAU).rem_euclid(0.5);
151        out[k] = (d, s);
152    }
153    Ok(out)
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    const F: f64 = 1e9;
161
162    #[test]
163    fn quarter_and_half_wave_sections_transform_impedances() {
164        let line = TransmissionLine::lossless(50.0, 0.66).unwrap();
165        let lambda = line.wavelength(F);
166        assert!((lambda - 0.66 * C0 / F).abs() < 1e-12);
167        let load = C64::new(100.0, 25.0);
168        let quarter = line.input_impedance(load, lambda / 4.0, F);
169        assert!((quarter - C64::new(2500.0, 0.0) / load).norm() < 1e-9);
170        assert!((line.input_impedance(load, lambda / 2.0, F) - load).norm() < 1e-8);
171        // Stubs: a shorted λ/8 stub is +j Z₀, an open λ/8 stub −j Z₀.
172        assert!((line.input_impedance(C64::new(0.0, 0.0), lambda / 8.0, F) - C64::new(0.0, 50.0)).norm() < 1e-9);
173        assert!((line.input_impedance(C64::new(f64::INFINITY, 0.0), lambda / 8.0, F) - C64::new(0.0, -50.0)).norm() < 1e-9);
174        assert_eq!(quarter_wave_transformer(50.0, 200.0), 100.0);
175    }
176
177    #[test]
178    fn reflection_metrics_and_standing_waves() {
179        let gamma = reflection_coefficient(C64::new(150.0, 0.0), C64::new(50.0, 0.0));
180        assert!((gamma.re - 0.5).abs() < 1e-15 && (vswr(gamma) - 3.0).abs() < 1e-12);
181        assert!((return_loss_db(gamma) - 6.0206).abs() < 1e-4 && (mismatch_loss_db(gamma) - 1.2494).abs() < 1e-4);
182        let line = TransmissionLine::lossless(50.0, 1.0).unwrap();
183        let lambda = line.wavelength(F);
184        let d: Vec<f64> = (0..200).map(|i| lambda * i as f64 / 200.0).collect();
185        let v = line.standing_wave(C64::new(150.0, 0.0), &d, F);
186        let (vmax, vmin) = v.iter().fold((0.0f64, f64::INFINITY), |(a, b), &x| (a.max(x), b.min(x)));
187        assert!((vmax / vmin - 3.0).abs() < 1e-3);
188        // A resistive load above Z₀ puts a voltage maximum at the load.
189        assert!((v[0] - vmax).abs() < 1e-9);
190    }
191
192    #[test]
193    fn lossy_lines_and_chain_matrices() {
194        // RG-58-like parameters: Z₀ near 50 Ω, a long line looks like Z₀ from the input.
195        let line = TransmissionLine::distributed(0.5, 250e-9, 1e-6, 100e-12).unwrap();
196        let z0 = line.characteristic_impedance(F);
197        assert!((z0.re - 50.0).abs() < 0.1 && z0.im.abs() < 0.1);
198        let far = line.input_impedance(C64::new(0.0, 0.0), 2000.0, F);
199        assert!((far - z0).norm() < 1e-3 * z0.norm());
200        assert!(line.propagation_constant(F).re > 0.0);
201        // The chain matrix reproduces the input impedance: Z_in = (A Z_L + B)/(C Z_L + D).
202        let load = C64::new(30.0, -20.0);
203        let m = line.abcd(0.37, F);
204        let zin = (m[0][0] * load + m[0][1]) / (m[1][0] * load + m[1][1]);
205        assert!((zin - line.input_impedance(load, 0.37, F)).norm() < 1e-9);
206        assert!(TransmissionLine::lossless(-1.0, 0.5).is_err());
207    }
208
209    #[test]
210    fn single_stub_matches_cancel_the_reflection() {
211        let z0 = 50.0;
212        let load = C64::new(25.0, 40.0);
213        let line = TransmissionLine::lossless(z0, 1.0).unwrap();
214        let lambda = line.wavelength(F);
215        for (d, s) in single_stub_match(load, z0).unwrap() {
216            let at_stub = line.input_impedance(load, d * lambda, F);
217            let stub = line.input_impedance(C64::new(0.0, 0.0), s * lambda, F);
218            let total = 1.0 / (1.0 / at_stub + 1.0 / stub);
219            assert!(reflection_coefficient(total, C64::new(z0, 0.0)).norm() < 1e-9, "d={d} s={s}");
220        }
221        assert!(single_stub_match(C64::new(-1.0, 0.0), z0).is_err());
222    }
223}