Skip to main content

lensbench_analysis/defs/
mod.rs

1//! 同梱の解析の定義(設定・結果の型と計算)。CLI・serve・GUI はここから作る([`crate::registry`])。
2//!
3//! 結果の JSON の形は GUI・Python のクライアントが鍵で読む約束(変えるときは壊れる変更として docs/changes.md に書く)。
4
5mod aber;
6mod basic;
7mod beam;
8mod illum;
9mod image;
10mod mtfs;
11
12/// 同梱の解析の結果の型(同じプロセスの呼び手は [`crate::Typed::get`] で引く。JSON は同じ形)
13pub use aber::{
14    CurvWave, DistKind, FanOut, FanRow, FieldCurvOut, GridOut, GridPoint, LatOut, LatWave, LongOut,
15    LongWave, SeidelOut, SeidelRow, SeidelWaves, ShiftOut,
16};
17pub use basic::{
18    GhostOut, GhostRow, RayCountsOut, SpotOut, SpotRow, WavefrontOut, WavefrontRow, ZKind,
19    ZernikeOut, ZernikeRow,
20};
21pub use beam::{GaussOut, GaussRow, Orientation as GaussOrientation};
22pub use illum::{mean_transmission, FootprintOut, FootprintRow, RelIllumOut, VignettingOut};
23pub use image::{
24    Plane as PsfPlane, PsfAxes, PsfOut, PsfPoint, PsfSampling, Reference as RmsReference, RmsOut,
25    RmsRow, Vs as RmsVs,
26};
27pub use mtfs::{FieldRow, FocusRow, GeoMtfOut, MtfFieldOut, MtfFocusOut, MtfOut};
28
29use lensbench_core::{Error, Result, System};
30use schemars::JsonSchema;
31use serde::{Deserialize, Serialize};
32
33use crate::registry::Analyses;
34
35/// 同梱の解析を登録する
36pub fn register(a: &mut Analyses) {
37    a.add(basic::Spot);
38    a.add(basic::Wavefront);
39    a.add(basic::Zernike);
40    a.add(basic::Ghost);
41    a.add(mtfs::Mtf);
42    a.add(mtfs::MtfFocus);
43    a.add(mtfs::MtfField);
44    a.add(mtfs::GeoMtf);
45    a.add(mtfs::HuygensMtf);
46    a.add(image::Rms);
47    a.add(image::Psf);
48    a.add(aber::RayFan);
49    a.add(aber::OpdFan);
50    a.add(aber::PupilFan);
51    a.add(aber::FieldCurv);
52    a.add(aber::Longitudinal);
53    a.add(aber::LateralColor);
54    a.add(aber::FocalShift);
55    a.add(aber::GridDistortion);
56    a.add(aber::SeidelCoef);
57    a.add(illum::Footprint);
58    a.add(illum::RelIllum);
59    a.add(illum::Vignetting);
60    a.add(beam::Gauss);
61}
62
63/// 視野の番号(1 始まり、None で全視野)を 0 始まりの並びにする
64pub fn fields(s: &System, field: Option<usize>) -> Result<Vec<usize>> {
65    match field {
66        None => Ok((0..s.fields.len()).collect()),
67        Some(i) if i >= 1 && i <= s.fields.len() => Ok(vec![i - 1]),
68        Some(i) => Err(Error::Invalid(format!(
69            "no field {i} (1 to {})",
70            s.fields.len()
71        ))),
72    }
73}
74
75/// 視野全体がけられた誤り(像面に届く光線が無い・主光線が届かず瞳を決められない)か
76pub fn field_vignetted(e: &Error) -> bool {
77    use lensbench_core::error::code;
78    matches!(e.code(), code::ALL_VIGNETTED | code::PUPIL_VIGNETTED)
79}
80
81/// 視野ごとの結果を集める。視野全体がけられた視野([`field_vignetted`])は飛ばして注意「field N: …」を `warn` に足し、
82/// ほかの視野の結果を返す(spot が全部けられた視野を空にするのと同じく、1 つの視野で解析全体を止めない)。
83/// どの視野も残らないときと、ほかの誤りはそのまま誤り
84pub(super) fn skip_vignetted<T>(
85    rows: Vec<(usize, Result<T>)>,
86    warn: &mut Vec<String>,
87) -> Result<Vec<T>> {
88    let (mut out, mut first) = (Vec::new(), None);
89    for (i, r) in rows {
90        match r {
91            Ok(x) => out.push(x),
92            Err(e) if field_vignetted(&e) => {
93                warn.push(format!("field {}: {e}", i + 1));
94                first.get_or_insert(e);
95            }
96            Err(e) => return Err(e),
97        }
98    }
99    match first {
100        Some(e) if out.is_empty() => Err(e),
101        _ => Ok(out),
102    }
103}
104
105/// 波長の番号(1 始まり、None で多色)を 0 始まりにする
106/// 設定 polarization の膜・偏光の振幅(系の入射偏光 `input_pol`、系の膜。[`crate::pupil_amp::PolAmp`])。off なら None
107fn pol_amp(
108    s: &System,
109    i: usize,
110    w: Option<usize>,
111    on: bool,
112) -> Result<Option<crate::pupil_amp::PolAmp>> {
113    if !on {
114        return Ok(None);
115    }
116    let co = lensbench_core::coating::Coatings::for_system(s)?;
117    let ws: Vec<usize> = w.map_or_else(|| (0..s.wavelengths.len()).collect(), |w| vec![w]);
118    let f = lensbench_core::FieldSel::Index(i);
119    crate::pupil_amp::PolAmp::new(
120        s,
121        f,
122        &ws,
123        &co,
124        crate::pupil_amp::POL_GRID,
125        s.input_pol.jones(),
126    )
127    .map(Some)
128}
129
130/// 膜を使う解析(polarization・ghost など)の結果の注意に足す、系の膜の注意(同じ名前の膜のどれを使ったかなど、
131/// [`lensbench_core::coating::Coatings::notes`])。on でなければ空
132fn coat_notes(s: &System, on: bool) -> Result<Vec<String>> {
133    if !on {
134        return Ok(Vec::new());
135    }
136    Ok(lensbench_core::coating::Coatings::for_system(s)?.notes)
137}
138
139pub fn wave(s: &System, w: Option<usize>) -> Result<Option<usize>> {
140    lensbench_core::waves::index_opt(w, s.wavelengths.len())
141}
142
143/// スポット・PSF の位置の単位: mm、アフォーカル像空間では角度の単位(前は mm を "lens" と書いた)
144fn spot_unit(s: &System) -> String {
145    s.image_unit().to_string()
146}
147
148/// 周波数の単位(cycles/mm、アフォーカル像空間では cycles/角度の単位)
149fn freq_unit(s: &System) -> String {
150    format!("cycles/{}", s.image_unit())
151}
152
153/// 0 から top までを steps 等分した周波数
154fn auto_freqs(top: f64, steps: usize) -> Result<Vec<f64>> {
155    if !(top.is_finite() && top > 0.0) {
156        return Err(Error::Invalid(format!("max_freq must be positive ({top})")));
157    }
158    if steps == 0 {
159        return Err(Error::Invalid("freq_steps must be 1 or more".into()));
160    }
161    Ok((0..=steps).map(|k| top * k as f64 / steps as f64).collect())
162}
163
164/// 周波数の選び方(与えた並び、または 0 から上限までの等分。上限の既定は子午・球欠の向き axes の遮断周波数の
165/// 小さい方の 0.95 倍)
166fn freqs_for(
167    s: &System,
168    field: usize,
169    w: Option<usize>,
170    freqs: &Option<Vec<f64>>,
171    max_freq: Option<f64>,
172    freq_steps: usize,
173    axes: MtfDirs,
174) -> Result<Vec<f64>> {
175    if let Some(f) = freqs {
176        if max_freq.is_some() {
177            return Err(Error::Invalid(
178                "freqs and max_freq can't be used together".into(),
179            ));
180        }
181        return Ok(f.clone());
182    }
183    let top = match max_freq {
184        Some(x) => x,
185        None => {
186            let f = lensbench_core::FieldSel::Index(field);
187            let w = w.unwrap_or(s.primary);
188            0.95 * crate::analysis::mtf_cutoff_axes(s, f, w, axes.core())?.min()
189        }
190    };
191    auto_freqs(top, freq_steps)
192}
193
194/// MTF の子午・球欠の向き(core の [`crate::analysis::MtfAxes`])
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
196#[serde(rename_all = "lowercase")]
197pub enum MtfDirs {
198    /// 子午は視野の向き(物理的な子午面)、球欠はそれに直交
199    #[default]
200    Field,
201    /// 子午は瞳の y、球欠は x の向き(OpticStudio の FFT MTF と同じ)
202    Pupil,
203}
204
205impl MtfDirs {
206    pub(super) fn core(self) -> crate::analysis::MtfAxes {
207        match self {
208            MtfDirs::Field => crate::analysis::MtfAxes::Field,
209            MtfDirs::Pupil => crate::analysis::MtfAxes::Pupil,
210        }
211    }
212}
213
214/// 視野を振る向き
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
216#[serde(rename_all = "lowercase")]
217pub enum Axis {
218    /// y の向き
219    #[default]
220    Y,
221    /// x の向き
222    X,
223}
224
225impl Axis {
226    fn core(self) -> crate::sweep::FieldAxis {
227        match self {
228            Axis::X => crate::sweep::FieldAxis::X,
229            Axis::Y => crate::sweep::FieldAxis::Y,
230        }
231    }
232}
233
234/// 回折 MTF の 1 視野(mtf・geo-mtf・huygens-mtf の共通の形)
235#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
236pub struct MtfRow {
237    /// Field number (from 1)
238    pub field: usize,
239    #[serde(deserialize_with = "crate::nan::v")]
240    pub freqs: Vec<f64>,
241    /// 子午
242    #[serde(deserialize_with = "crate::nan::v")]
243    pub tangential: Vec<f64>,
244    /// 球欠
245    #[serde(deserialize_with = "crate::nan::v")]
246    pub sagittal: Vec<f64>,
247    /// 回折限界の遮断周波数 [cycles/mm](計算した波長。多色は主波長)
248    pub cutoff: Cutoff,
249    /// 波長ごと(mtf の each_wave)
250    #[serde(skip_serializing_if = "Option::is_none")]
251    pub waves: Option<Vec<WaveMtf>>,
252}
253
254/// 子午・球欠の遮断周波数
255#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
256pub struct Cutoff {
257    #[serde(deserialize_with = "crate::nan::f")]
258    pub tangential: f64,
259    #[serde(deserialize_with = "crate::nan::f")]
260    pub sagittal: f64,
261}
262
263/// 1 波長の MTF
264#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
265pub struct WaveMtf {
266    /// 波長の番号(1 始まり)
267    pub wave: usize,
268    #[serde(deserialize_with = "crate::nan::v")]
269    pub tangential: Vec<f64>,
270    #[serde(deserialize_with = "crate::nan::v")]
271    pub sagittal: Vec<f64>,
272}
273
274impl MtfRow {
275    fn of(field: usize, m: crate::analysis::Mtf) -> MtfRow {
276        MtfRow {
277            field: field + 1,
278            freqs: m.freqs,
279            tangential: m.tan,
280            sagittal: m.sag,
281            cutoff: Cutoff {
282                tangential: m.cutoff.tan,
283                sagittal: m.cutoff.sag,
284            },
285            waves: None,
286        }
287    }
288}
289
290#[cfg(test)]
291mod tests;