Skip to main content

lensbench_core/
grid.rs

1//! 2 次元の格子の値。解析の 2 次元の結果(波面・PSF・干渉縞など)は全部この形で持つ。
2//!
3//! 値は行優先の平らな並び(行 = y、`data[iy * nx + ix]`)で、各軸の座標を並びで持つ(標本 i の座標 `x[i]`)。
4//! Python へは写さずに numpy の (ny, nx) の配列にでき、プラグインの配列への変換も 1 つで済む。
5
6/// 2 次元の格子の値。座標の並び x(長さ nx)・y(長さ ny)と、行優先の値 data(長さ nx·ny、行 = y)
7#[derive(Debug, Clone, PartialEq)]
8pub struct Grid2<T = f64> {
9    x: Vec<f64>,
10    y: Vec<f64>,
11    data: Vec<T>,
12}
13
14impl<T> Grid2<T> {
15    /// 座標と行優先の値から作る(長さが合わなければ panic: 作る側の誤り)
16    pub fn new(x: Vec<f64>, y: Vec<f64>, data: Vec<T>) -> Self {
17        assert_eq!(
18            data.len(),
19            x.len() * y.len(),
20            "Grid2: {} values for {} × {}",
21            data.len(),
22            x.len(),
23            y.len()
24        );
25        Grid2 { x, y, data }
26    }
27
28    /// 行の並び(`rows[iy][ix]`)から作る
29    pub fn from_rows(x: Vec<f64>, y: Vec<f64>, rows: Vec<Vec<T>>) -> Self {
30        assert!(
31            rows.len() == y.len() && rows.iter().all(|r| r.len() == x.len()),
32            "Grid2: rows do not match {} × {}",
33            x.len(),
34            y.len()
35        );
36        let data = rows.into_iter().flatten().collect();
37        Grid2 { x, y, data }
38    }
39
40    /// x の標本の数(列の数)
41    pub fn nx(&self) -> usize {
42        self.x.len()
43    }
44
45    /// y の標本の数(行の数)
46    pub fn ny(&self) -> usize {
47        self.y.len()
48    }
49
50    /// x の座標の並び
51    pub fn x(&self) -> &[f64] {
52        &self.x
53    }
54
55    /// y の座標の並び
56    pub fn y(&self) -> &[f64] {
57        &self.y
58    }
59
60    /// 行優先の値(`data[iy * nx + ix]`)
61    pub fn data(&self) -> &[T] {
62        &self.data
63    }
64
65    pub fn data_mut(&mut self) -> &mut [T] {
66        &mut self.data
67    }
68
69    /// (x, y, 行優先の値) に分ける
70    pub fn into_parts(self) -> (Vec<f64>, Vec<f64>, Vec<T>) {
71        (self.x, self.y, self.data)
72    }
73
74    /// 値 (ix, iy)
75    pub fn get(&self, ix: usize, iy: usize) -> &T {
76        assert!(ix < self.nx(), "Grid2: ix {ix} ≥ {}", self.nx());
77        &self.data[iy * self.nx() + ix]
78    }
79
80    /// 行 iy(y = `y[iy]` の値の並び)
81    pub fn row(&self, iy: usize) -> &[T] {
82        let n = self.nx();
83        &self.data[iy * n..(iy + 1) * n]
84    }
85
86    /// 行の並び(y の順)
87    pub fn rows(&self) -> impl ExactSizeIterator<Item = &[T]> + '_ {
88        // nx = 0 でも ny 行を返す
89        (0..self.ny()).map(move |iy| self.row(iy))
90    }
91
92    /// 値ごとに f をかけた同じ座標の格子
93    pub fn map<U>(&self, f: impl FnMut(&T) -> U) -> Grid2<U> {
94        Grid2 {
95            x: self.x.clone(),
96            y: self.y.clone(),
97            data: self.data.iter().map(f).collect(),
98        }
99    }
100}
101
102/// 行 iy(`g[iy][ix]` で値を引ける)
103impl<T> std::ops::Index<usize> for Grid2<T> {
104    type Output = [T];
105    fn index(&self, iy: usize) -> &[T] {
106        self.row(iy)
107    }
108}
109
110impl<T> std::ops::IndexMut<usize> for Grid2<T> {
111    fn index_mut(&mut self, iy: usize) -> &mut [T] {
112        let n = self.nx();
113        &mut self.data[iy * n..(iy + 1) * n]
114    }
115}
116
117impl<T: Clone> Grid2<T> {
118    /// 行の並び(`rows[iy][ix]`)に写す
119    pub fn to_rows(&self) -> Vec<Vec<T>> {
120        self.rows().map(<[T]>::to_vec).collect()
121    }
122}
123
124impl Grid2<f64> {
125    /// 有限の値の最大(無ければ −∞)
126    pub fn max(&self) -> f64 {
127        self.data
128            .iter()
129            .copied()
130            .filter(|v| v.is_finite())
131            .fold(f64::NEG_INFINITY, f64::max)
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn rows_and_flat_agree() {
141        let g = Grid2::from_rows(
142            vec![0.0, 1.0, 2.0],
143            vec![10.0, 20.0],
144            vec![vec![1, 2, 3], vec![4, 5, 6]],
145        );
146        assert_eq!((g.nx(), g.ny()), (3, 2));
147        assert_eq!(g.data(), &[1, 2, 3, 4, 5, 6]);
148        assert_eq!(*g.get(2, 1), 6);
149        assert_eq!(g.row(1), &[4, 5, 6]);
150        assert_eq!(g[1][2], 6);
151        assert_eq!(g.to_rows(), vec![vec![1, 2, 3], vec![4, 5, 6]]);
152        assert_eq!(g.map(|v| v * 2).data(), &[2, 4, 6, 8, 10, 12]);
153        let e: Grid2<f64> = Grid2::new(Vec::new(), vec![0.0, 1.0], Vec::new());
154        assert_eq!(e.rows().len(), 2);
155    }
156
157    #[test]
158    #[should_panic]
159    fn wrong_length_panics() {
160        Grid2::new(vec![0.0], vec![0.0, 1.0], vec![1.0]);
161    }
162}