Skip to main content

lib_jsl_electromagnetics/signal_models/
distributed.rs

1//! Distributed sources: brightness- or noise-temperature distributions over the sky.
2//!
3//! See the book entry [Arrays, scenes and beamformers](https://jwkunz.github.io/lib_jsl/book/em-arrays/beamforming.html).
4
5use super::Coherency;
6use crate::arrays::SensorArray;
7use crate::conventions::C64;
8use crate::fields::domain::Domain;
9use crate::fields::field_container::{FieldQuantity, HarmonicField};
10use lib_jsl_core::ErrorsJSL;
11use lib_jsl_core::constants::physics::K_B;
12use ndarray::Array2;
13use std::f64::consts::PI;
14use std::sync::Arc;
15
16/// How the distributed emission is polarized.
17#[derive(Debug, Clone, Copy, PartialEq)]
18pub enum SkyPolarization {
19    /// Unpolarized emission (thermal noise): each polarization carries the brightness temperature.
20    Unpolarized,
21    /// Partially or fully polarized emission with unit-trace coherency `J`; the total brightness
22    /// `2T` is shared between the polarizations according to `J` (so `J = ½ I` is unpolarized).
23    Polarized(Coherency),
24}
25
26/// A brightness-temperature map `T(Ω)` (K) on a far-field domain: the sky, the ground, a hot
27/// spot, any spatially distributed thermal scene. The map's domain also sets the quadrature used
28/// to integrate it.
29#[derive(Debug, Clone)]
30pub struct BrightnessScene {
31    temperature: Arc<HarmonicField>,
32    polarization: SkyPolarization,
33}
34
35impl BrightnessScene {
36    /// A scene from a scalar temperature field on a far-field domain (the real parts are used).
37    pub fn new(temperature: Arc<HarmonicField>, polarization: SkyPolarization) -> Result<Self, ErrorsJSL> {
38        if !temperature.domain().is_far_field() || !temperature.is_scalar() || temperature.quantity() != FieldQuantity::Temperature {
39            return Err(ErrorsJSL::InvalidInputRange("A brightness scene needs a scalar temperature map on the far-field sphere."));
40        }
41        if temperature.values().iter().any(|v| !(v.re.is_finite() && v.re >= 0.0)) {
42            return Err(ErrorsJSL::InvalidInputRange("Brightness temperatures must be finite and non-negative."));
43        }
44        Ok(BrightnessScene { temperature, polarization })
45    }
46
47    /// A map built from a function `T(θ, φ)` on `domain`, at the array's frequency (the value is
48    /// only a tag for the container; temperatures are frequency-independent here).
49    pub fn from_fn(domain: Arc<Domain>, frequency: f64, polarization: SkyPolarization, t: impl Fn(f64, f64) -> f64) -> Result<Self, ErrorsJSL> {
50        let map = HarmonicField::scalar_from_fn(domain, FieldQuantity::Temperature, frequency, crate::conventions::TimeConvention::PlusJ, |p| C64::new(t(p.coords[1], p.coords[2]), 0.0))?;
51        Self::new(Arc::new(map), polarization)
52    }
53
54    pub fn temperature_map(&self) -> &Arc<HarmonicField> {
55        &self.temperature
56    }
57
58    /// The covariance `R = k_B B / (4π) ∫ T(Ω) A(Ω) M A(Ω)ᴴ dΩ` (W) over bandwidth `B`, with
59    /// `M = I` for unpolarized emission and `2J` for polarized. A single co-polarized element
60    /// therefore sees `k_B B T_A` with the antenna temperature `T_A = (1/4π) ∫ G T dΩ`.
61    pub fn covariance(&self, array: &SensorArray, bandwidth: f64) -> Result<Array2<C64>, ErrorsJSL> {
62        if !bandwidth.is_finite() || bandwidth <= 0.0 {
63            return Err(ErrorsJSL::InvalidInputRange("The bandwidth must be positive."));
64        }
65        let m: [[C64; 2]; 2] = match self.polarization {
66            SkyPolarization::Unpolarized => [[C64::new(1.0, 0.0), C64::new(0.0, 0.0)], [C64::new(0.0, 0.0), C64::new(1.0, 0.0)]],
67            SkyPolarization::Polarized(j) => j.0.map(|row| row.map(|v| v * 2.0)),
68        };
69        let n = array.len();
70        let domain = self.temperature.domain();
71        let mut r = Array2::<C64>::zeros((n, n));
72        for i in 0..domain.len() {
73            let t = self.temperature.scalar(i).re;
74            let w = domain.weights()[i] * t;
75            if w == 0.0 {
76                continue;
77            }
78            let p = domain.position_flat(i);
79            let a = array.response_matrix(p.coords[1], p.coords[2])?;
80            // A M Aᴴ, accumulated.
81            for row in 0..n {
82                let am = [a[[row, 0]] * m[0][0] + a[[row, 1]] * m[1][0], a[[row, 0]] * m[0][1] + a[[row, 1]] * m[1][1]];
83                for col in 0..n {
84                    r[[row, col]] += (am[0] * a[[col, 0]].conj() + am[1] * a[[col, 1]].conj()) * w;
85                }
86            }
87        }
88        Ok(r.mapv(|v| v * (K_B * bandwidth / (4.0 * PI))))
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use crate::antenna_models::{HalfWaveDipole, Isotropic};
96    use crate::conventions::TimeConvention;
97    use crate::coordinates::transforms::RigidTransform;
98    use crate::signal_models::PointSource;
99    use lib_jsl_core::constants::em::C0;
100
101    #[test]
102    fn uniform_sky_gives_k_t_b_per_element_regardless_of_the_pattern() {
103        let f = 1e9;
104        let b = 1e6;
105        let sky = BrightnessScene::from_fn(Arc::new(Domain::far_field_gauss(40, 80).unwrap()), f, SkyPolarization::Unpolarized, |_, _| 290.0).unwrap();
106        for antenna in [Arc::new(Isotropic::theta_polarized()) as Arc<dyn crate::antenna_models::Antenna + Send + Sync>, Arc::new(HalfWaveDipole::new(f))] {
107            let array = SensorArray::from_antenna(&[[0.0; 3]], antenna, &RigidTransform::identity(), f, TimeConvention::PlusJ, 1.0).unwrap();
108            let r = sky.covariance(&array, b).unwrap();
109            // ∫ G dΩ = 4π for a lossless antenna, so T_A = T.
110            assert!((r[[0, 0]].re - K_B * b * 290.0).abs() < 2e-3 * K_B * b * 290.0, "{}", r[[0, 0]].re / (K_B * b));
111        }
112    }
113
114    #[test]
115    fn a_small_hot_spot_matches_the_equivalent_point_source() {
116        // Rayleigh-Jeans: a patch of brightness T over solid angle ΔΩ has flux S = 2 k_B T ΔΩ B / λ²
117        // (both polarizations); the distributed and point-source models must agree.
118        let f = 1e9;
119        let lambda = C0 / f;
120        let b = 1e6;
121        let d = Arc::new(Domain::far_field_uniform(181, 360).unwrap());
122        let (t0, p0) = (d.position(&[60, 45]).coords[1], d.position(&[60, 45]).coords[2]);
123        let spot = BrightnessScene::from_fn(d.clone(), f, SkyPolarization::Unpolarized, |t, p| if (t - t0).abs() < 1e-9 && (p - p0).abs() < 1e-9 { 1000.0 } else { 0.0 }).unwrap();
124        let omega = d.weights()[d.flatten(&[60, 45])];
125        let array = SensorArray::from_antenna(&SensorArray::linear_positions(3, lambda / 2.0, [1.0, 0.0, 0.0]), Arc::new(Isotropic::theta_polarized()), &RigidTransform::identity(), f, TimeConvention::PlusJ, 1.0).unwrap();
126        let r_spot = spot.covariance(&array, b).unwrap();
127        let point = PointSource::new(t0, p0, 2.0 * K_B * 1000.0 * omega * b / (lambda * lambda), Coherency::unpolarized()).unwrap();
128        let r_point = point.covariance(&array).unwrap();
129        assert!(r_spot.iter().zip(r_point.iter()).all(|(a, c)| (a - c).norm() < 1e-9 * r_point[[0, 0]].norm()));
130        // Validation.
131        let scalar_e = HarmonicField::zeros(d.clone(), FieldQuantity::Generic, crate::fields::field_container::Rank::Scalar, f, TimeConvention::PlusJ).unwrap();
132        assert!(BrightnessScene::new(Arc::new(scalar_e), SkyPolarization::Unpolarized).is_err());
133        assert!(BrightnessScene::from_fn(d.clone(), f, SkyPolarization::Unpolarized, |_, _| -1.0).is_err());
134        assert!(spot.covariance(&array, 0.0).is_err());
135        let polarized = BrightnessScene::from_fn(d, f, SkyPolarization::Polarized(Coherency::phi()), |_, _| 10.0).unwrap();
136        assert!(polarized.covariance(&array, b).unwrap().iter().all(|v| v.norm() < 1e-25)); // θ-pol elements see nothing
137    }
138}