lib_jsl_electromagnetics/signal_models/
covariance.rs1use super::distributed::BrightnessScene;
6use super::point_source::PointSource;
7use crate::arrays::SensorArray;
8use crate::conventions::C64;
9use crate::linalg::{check_hermitian, hermitian_eigen};
10use lib_jsl_core::ErrorsJSL;
11use lib_jsl_core::constants::physics::K_B;
12use lib_jsl_random::distributions::gaussian::gaussian_distribution_box_muller;
13use lib_jsl_random::xoshiro256plusplus::Xoshiro256PlusPlus;
14use ndarray::Array2;
15
16#[derive(Debug, Clone)]
19pub struct Scene {
20 pub bandwidth: f64,
21 pub point_sources: Vec<PointSource>,
22 pub distributed: Vec<BrightnessScene>,
23 pub receiver_temperature: f64,
24}
25
26impl Scene {
27 pub fn new(bandwidth: f64) -> Result<Self, ErrorsJSL> {
28 if !bandwidth.is_finite() || bandwidth <= 0.0 {
29 return Err(ErrorsJSL::InvalidInputRange("The bandwidth must be positive."));
30 }
31 Ok(Scene { bandwidth, point_sources: Vec::new(), distributed: Vec::new(), receiver_temperature: 0.0 })
32 }
33
34 pub fn with_point_source(mut self, source: PointSource) -> Self {
35 self.point_sources.push(source);
36 self
37 }
38
39 pub fn with_distributed(mut self, scene: BrightnessScene) -> Self {
40 self.distributed.push(scene);
41 self
42 }
43
44 pub fn with_receiver_temperature(mut self, temperature: f64) -> Self {
45 self.receiver_temperature = temperature;
46 self
47 }
48
49 pub fn receiver_noise_covariance(&self, array: &SensorArray) -> Array2<C64> {
51 Array2::from_diag_elem(array.len(), C64::new(K_B * self.receiver_temperature * self.bandwidth, 0.0))
52 }
53
54 pub fn point_source_covariance(&self, array: &SensorArray) -> Result<Array2<C64>, ErrorsJSL> {
56 let mut r = Array2::<C64>::zeros((array.len(), array.len()));
57 for s in &self.point_sources {
58 r += &s.covariance(array)?;
59 }
60 Ok(r)
61 }
62
63 pub fn distributed_covariance(&self, array: &SensorArray) -> Result<Array2<C64>, ErrorsJSL> {
65 let mut r = Array2::<C64>::zeros((array.len(), array.len()));
66 for s in &self.distributed {
67 r += &s.covariance(array, self.bandwidth)?;
68 }
69 Ok(r)
70 }
71
72 pub fn covariance(&self, array: &SensorArray) -> Result<Array2<C64>, ErrorsJSL> {
74 Ok(self.point_source_covariance(array)? + self.distributed_covariance(array)? + self.receiver_noise_covariance(array))
75 }
76}
77
78pub fn sample_covariance(snapshots: &Array2<C64>) -> Result<Array2<C64>, ErrorsJSL> {
80 let k = snapshots.ncols();
81 if k == 0 || snapshots.nrows() == 0 {
82 return Err(ErrorsJSL::InvalidInputRange("Need at least one snapshot of at least one channel."));
83 }
84 Ok(snapshots.dot(&snapshots.t().mapv(|v| v.conj())) / C64::new(k as f64, 0.0))
85}
86
87pub fn synthesize_snapshots(r: &Array2<C64>, count: usize, seed: u64) -> Result<Array2<C64>, ErrorsJSL> {
91 let n = r.nrows();
92 check_hermitian(r, n)?;
93 let (vals, vecs) = hermitian_eigen(r)?;
94 let scale: Vec<f64> = vals.iter().map(|&v| v.max(0.0).sqrt()).collect();
95 let mut rng = Xoshiro256PlusPlus::from_seed(seed);
96 let mut out = Array2::<C64>::zeros((n, count));
97 for c in 0..count {
98 let z: Vec<C64> = (0..n)
99 .map(|_| loop {
100 let (a, b) = gaussian_distribution_box_muller(&mut rng, 0.0, std::f64::consts::FRAC_1_SQRT_2);
101 if a.is_finite() && b.is_finite() {
102 break C64::new(a, b);
103 }
104 })
105 .collect();
106 for i in 0..n {
107 out[[i, c]] = (0..n).map(|k| vecs[[i, k]] * scale[k] * z[k]).sum();
108 }
109 }
110 Ok(out)
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116 use crate::antenna_models::Isotropic;
117 use crate::conventions::TimeConvention;
118 use crate::coordinates::transforms::RigidTransform;
119 use crate::fields::domain::Domain;
120 use crate::signal_models::{Coherency, SkyPolarization};
121 use lib_jsl_core::constants::em::C0;
122 use std::sync::Arc;
123
124 fn array() -> SensorArray {
125 let f = 1e9;
126 SensorArray::from_antenna(&SensorArray::linear_positions(4, 0.5 * C0 / f, [1.0, 0.0, 0.0]), Arc::new(Isotropic::theta_polarized()), &RigidTransform::identity(), f, TimeConvention::PlusJ, 1.0).unwrap()
127 }
128
129 #[test]
130 fn scene_covariance_is_the_sum_of_its_parts_and_hermitian() {
131 let a = array();
132 let sky = BrightnessScene::from_fn(Arc::new(Domain::far_field_gauss(20, 40).unwrap()), 1e9, SkyPolarization::Unpolarized, |t, _| if t > 1.6 { 290.0 } else { 10.0 }).unwrap();
133 let scene = Scene::new(1e6).unwrap().with_point_source(PointSource::new(0.8, 0.3, 1e-15, Coherency::theta()).unwrap()).with_distributed(sky).with_receiver_temperature(50.0);
134 let r = scene.covariance(&a).unwrap();
135 let parts = scene.point_source_covariance(&a).unwrap() + scene.distributed_covariance(&a).unwrap() + scene.receiver_noise_covariance(&a);
136 assert!(r.iter().zip(parts.iter()).all(|(x, y)| (x - y).norm() < 1e-30));
137 assert!(check_hermitian(&r, 4).is_ok());
138 let (vals, _) = hermitian_eigen(&r).unwrap();
140 assert!(vals.iter().all(|&v| v > 0.0));
141 assert!(Scene::new(0.0).is_err());
142 }
143
144 #[test]
145 fn snapshots_reproduce_the_covariance() {
146 let a = array();
147 let scene = Scene::new(1e6).unwrap().with_point_source(PointSource::new(1.1, 0.2, 1e-14, Coherency::theta()).unwrap()).with_receiver_temperature(100.0);
148 let r = scene.covariance(&a).unwrap();
149 let x = synthesize_snapshots(&r, 20_000, 7).unwrap();
150 let est = sample_covariance(&x).unwrap();
151 let scale = r[[0, 0]].norm();
152 let worst = r.iter().zip(est.iter()).map(|(p, q)| (p - q).norm()).fold(0.0, f64::max);
153 assert!(worst < 0.05 * scale, "{}", worst / scale);
154 assert_eq!(synthesize_snapshots(&r, 3, 7).unwrap(), synthesize_snapshots(&r, 3, 7).unwrap());
155 assert!(sample_covariance(&Array2::zeros((2, 0))).is_err());
156 assert!(synthesize_snapshots(&Array2::from_shape_fn((2, 2), |(i, j)| C64::new(0.0, (i as f64) - (j as f64) + 1.0)), 1, 1).is_err());
157 }
158}