1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//! # M1 & M2 Rigid Body Motions to Linear Optical Model
//!
//! Transforms M1 and M2 rigid body motions to optical metrics
//! (tip-tilt, segment piston and  segment tip-tilt) using
//! linear optical sensitivity matrices

use std::{io::Read, path::Path, sync::Arc};

use flate2::bufread::GzDecoder;
use gmt_dos_clients_io::{
    gmt_m1::M1RigidBodyMotions,
    gmt_m2::{asm::M2ASMReferenceBodyNodes, M2RigidBodyMotions},
    optics::{
        MaskedWavefront, SegmentD21PistonRSS, SegmentPiston, SegmentTipTilt, SegmentWfeRms,
        TipTilt, Wavefront, WfeRms,
    },
};
use gmt_lom::{LinearOpticalModelError, Loader, LOM};
use interface::{self, Data, Size, Units, Update, Write};

mod optical_sensitivity;
pub use optical_sensitivity::OpticalSensitivities;

/// M1 & M2 Rigid Body Motions to Linear Optical Model
#[derive(Debug, Clone)]
pub struct LinearOpticalModel {
    lom: LOM,
    m1_rbm: Arc<Vec<f64>>,
    m2_rbm: Arc<Vec<f64>>,
}
impl LinearOpticalModel {
    pub fn new() -> std::result::Result<Self, LinearOpticalModelError> {
        let sens = include_bytes!("optical_sensitivities.rs.bin.gz");
        let mut gz = GzDecoder::new(sens.as_slice());
        let mut bytes = vec![];
        gz.read_to_end(&mut bytes)?;
        Ok(Self {
            lom: LOM::try_from(bytes.as_slice())?,
            m1_rbm: Arc::new(vec![0f64; 42]),
            m2_rbm: Arc::new(vec![0f64; 42]),
        })
    }
    pub fn new_with_path(
        path: impl AsRef<Path>,
    ) -> std::result::Result<Self, LinearOpticalModelError> {
        let path = path.as_ref();
        let filename = path.file_name().unwrap();
        let sens_loader = Loader::<gmt_lom::OpticalSensitivities>::default()
            .path(path.parent().unwrap())
            .filename(filename.to_str().unwrap());
        Ok(Self {
            lom: LOM::builder()
                .load_optical_sensitivities(sens_loader)?
                .build()?,
            m1_rbm: Arc::new(vec![0f64; 42]),
            m2_rbm: Arc::new(vec![0f64; 42]),
        })
    }
}

impl Units for LinearOpticalModel {}

impl Update for LinearOpticalModel {
    fn update(&mut self) {
        self.lom.rbm = vec![(self.m1_rbm.as_slice(), self.m2_rbm.as_slice())]
            .into_iter()
            .collect();
    }
}
impl interface::Read<M1RigidBodyMotions> for LinearOpticalModel {
    fn read(&mut self, data: Data<M1RigidBodyMotions>) {
        self.m1_rbm = data.into_arc();
    }
}
impl interface::Read<M2RigidBodyMotions> for LinearOpticalModel {
    fn read(&mut self, data: Data<M2RigidBodyMotions>) {
        self.m2_rbm = data.into_arc();
    }
}
impl interface::Read<M2ASMReferenceBodyNodes> for LinearOpticalModel {
    fn read(&mut self, data: Data<M2ASMReferenceBodyNodes>) {
        self.m2_rbm = data.into_arc();
    }
}

impl Write<TipTilt> for LinearOpticalModel {
    fn write(&mut self) -> Option<Data<TipTilt>> {
        Some(Data::new(self.lom.tiptilt().into()))
    }
}
impl Write<SegmentTipTilt> for LinearOpticalModel {
    fn write(&mut self) -> Option<Data<SegmentTipTilt>> {
        Some(Data::new(self.lom.segment_tiptilt().into()))
    }
}
impl<const E: i32> Write<SegmentPiston<E>> for LinearOpticalModel {
    fn write(&mut self) -> Option<Data<SegmentPiston<E>>> {
        let mut piston: Vec<f64> = self.lom.segment_piston().into();
        if E != 0 {
            piston.iter_mut().for_each(|p| {
                *p *= 10f64.powi(-E);
            });
        }
        Some(piston.into())
    }
}
impl<const E: i32> Write<SegmentWfeRms<E>> for LinearOpticalModel {
    fn write(&mut self) -> Option<Data<SegmentWfeRms<E>>> {
        Some(self.lom.segment_wfe_rms::<E>().into())
    }
}
impl<const E: i32> Write<SegmentD21PistonRSS<E>> for LinearOpticalModel {
    fn write(&mut self) -> Option<Data<SegmentD21PistonRSS<E>>> {
        let piston: Vec<f64> = self.lom.segment_piston().into();
        let mut sum_squared = 0f64;
        for p_i in piston.iter().take(6) {
            for p_j in piston.iter().skip(1) {
                sum_squared += (p_i - p_j).powi(2);
            }
        }
        let mut rss = sum_squared.sqrt();
        if E != 0 {
            rss *= 10f64.powi(-E);
        }
        Some(vec![rss].into())
    }
}

impl Write<Wavefront> for LinearOpticalModel {
    fn write(&mut self) -> Option<Data<Wavefront>> {
        Some(Data::new(self.lom.wavefront().into()))
    }
}

impl Write<MaskedWavefront> for LinearOpticalModel {
    fn write(&mut self) -> Option<Data<MaskedWavefront>> {
        Some(Data::new(self.lom.masked_wavefront().into()))
    }
}

impl<const E: i32> Write<WfeRms<E>> for LinearOpticalModel {
    fn write(&mut self) -> Option<Data<WfeRms<E>>> {
        let wavefront = self.lom.masked_wavefront();
        let n = wavefront.len() as f64;
        let (s, m) = wavefront
            .into_iter()
            .fold((0f64, 0f64), |(mut s, mut m), w| {
                s += w * w;
                m += w;
                (s, m)
            });
        let mut wfe_rms = ((s - m * m / n) / n).sqrt();
        if E != 0 {
            wfe_rms *= 10f64.powi(-E);
        }
        Some(Data::new(vec![wfe_rms]))
    }
}

impl Size<TipTilt> for LinearOpticalModel {
    fn len(&self) -> usize {
        2
    }
}
impl Size<SegmentTipTilt> for LinearOpticalModel {
    fn len(&self) -> usize {
        14
    }
}
impl Size<SegmentPiston> for LinearOpticalModel {
    fn len(&self) -> usize {
        7
    }
}
impl Size<Wavefront> for LinearOpticalModel {
    fn len(&self) -> usize {
        512 * 512
    }
}
impl Size<WfeRms> for LinearOpticalModel {
    fn len(&self) -> usize {
        1
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn m1_segment_rxy() {
        let mut rbm2lom = LinearOpticalModel::new().unwrap();
        let s = 1e-6;
        let m1_rbm: Vec<_> = (0..7)
            .flat_map(|_| {
                let mut v = vec![0f64; 6];
                v[3] = s;
                v
            })
            .collect();
        <LinearOpticalModel as interface::Read<M1RigidBodyMotions>>::read(
            &mut rbm2lom,
            m1_rbm.into(),
        );
        rbm2lom.update();
        let mut stt: Vec<f64> = <LinearOpticalModel as Write<SegmentTipTilt>>::write(&mut rbm2lom)
            .unwrap()
            .into();
        stt.iter_mut().for_each(|x| *x /= s);
        let stt_mag: Vec<_> = stt[..7]
            .iter()
            .zip(&stt[7..])
            .map(|(x, y)| x.hypot(*y))
            .collect();
        println!("STT: {:.2?}", stt_mag);
    }

    #[test]
    fn m2_segment_rxy() {
        let mut rbm2lom = LinearOpticalModel::new().unwrap();
        let s = 1e-6;
        let m1_rbm: Vec<_> = (0..7)
            .flat_map(|_| {
                let mut v = vec![0f64; 6];
                v[4] = s;
                v
            })
            .collect();
        <LinearOpticalModel as interface::Read<M2RigidBodyMotions>>::read(
            &mut rbm2lom,
            m1_rbm.into(),
        );
        rbm2lom.update();
        let mut stt: Vec<f64> = <LinearOpticalModel as Write<SegmentTipTilt>>::write(&mut rbm2lom)
            .unwrap()
            .into();
        stt.iter_mut().for_each(|x| *x /= s);
        let stt_mag: Vec<_> = stt[..7]
            .iter()
            .zip(&stt[7..])
            .map(|(x, y)| x.hypot(*y))
            .collect();
        println!("STT: {:.2?}", stt_mag);
    }

    #[test]
    fn m1_segment_txy() {
        let mut rbm2lom = LinearOpticalModel::new().unwrap();
        let s = 1e-6;
        let m1_rbm: Vec<_> = (0..7)
            .flat_map(|_| {
                let mut v = vec![0f64; 6];
                v[0] = s;
                v
            })
            .collect();
        <LinearOpticalModel as interface::Read<M1RigidBodyMotions>>::read(
            &mut rbm2lom,
            m1_rbm.into(),
        );
        rbm2lom.update();
        let mut stt: Vec<f64> = <LinearOpticalModel as Write<SegmentTipTilt>>::write(&mut rbm2lom)
            .unwrap()
            .into();
        stt.iter_mut().for_each(|x| *x /= s);
        let stt_mag: Vec<_> = stt[..7]
            .iter()
            .zip(&stt[7..])
            .map(|(x, y)| x.hypot(*y))
            .collect();
        println!("STT: {:.3?}", stt_mag);
    }
}