qualia_core_db/sensing/acquisition/
correlation.rs1use super::*;
2#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3pub enum ProductConvention {
4 LeftTimesConjugateRight,
5 ConjugateLeftTimesRight,
6 LeftTimesRight,
7}
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum Normalization {
10 Sum,
11 Mean { contributing_pairs: u64 },
12 Reported(ArtifactLink),
13}
14#[derive(Clone, Copy, Debug)]
17pub struct CorrelationView<'a> {
18 tensor: TensorView<'a>,
19 clock: Clock,
20 first_lag: i64,
21 lag_step: i64,
22 product: ProductConvention,
23 normalization: Normalization,
24}
25impl<'a> CorrelationView<'a> {
26 pub fn admit(
27 tensor: TensorView<'a>,
28 clock: Clock,
29 first_lag: i64,
30 lag_step: i64,
31 product: ProductConvention,
32 normalization: Normalization,
33 ) -> Result<Self, Error> {
34 let l = tensor.layout();
35 if l.rank != 3
36 || l.axes[..3] != [Axis::Lag, Axis::LeftChannel, Axis::RightChannel]
37 || !l.encoding.complex()
38 || lag_step == 0
39 || tensor.clock().is_some()
40 {
41 return Err(Error::Shape);
42 }
43 match normalization {
44 Normalization::Mean {
45 contributing_pairs: 0,
46 } => return Err(Error::Semantics),
47 Normalization::Reported(r) => r.validate()?,
48 _ => (),
49 }
50 let view = Self {
51 tensor,
52 clock,
53 first_lag,
54 lag_step,
55 product,
56 normalization,
57 };
58 view.lag_ticks(l.extents[0] - 1)?;
59 Ok(view)
60 }
61 pub fn lag_ticks(self, index: u32) -> Result<i64, Error> {
63 if index >= self.tensor.layout().extents[0] {
64 return Err(Error::Bounds);
65 }
66 self.lag_step
67 .checked_mul(i64::from(index))
68 .and_then(|x| self.first_lag.checked_add(x))
69 .ok_or(Error::Overflow)
70 }
71 pub fn lag_seconds(self, index: u32) -> Result<ExactTime, Error> {
73 let ticks = self.lag_ticks(index)?;
74 let r = self.clock.timing().ticks;
75 let n = i128::from(ticks)
76 .checked_mul(i128::from(r.denominator))
77 .ok_or(Error::Overflow)?;
78 let mut a = n.unsigned_abs();
79 let mut b = u128::from(r.numerator);
80 while b != 0 {
81 let c = a % b;
82 a = b;
83 b = c;
84 }
85 Ok(ExactTime {
86 numerator: n / (a as i128),
87 denominator: i128::from(r.numerator) / (a as i128),
88 })
89 }
90 pub fn tensor(self) -> TensorView<'a> {
91 self.tensor
92 }
93 pub fn clock(self) -> Clock {
94 self.clock
95 }
96 pub fn lag_step_ticks(self) -> i64 {
97 self.lag_step
98 }
99 pub fn product(self) -> ProductConvention {
100 self.product
101 }
102 pub fn normalization(self) -> Normalization {
103 self.normalization
104 }
105}