Skip to main content

lensbench_analysis/
plugins.rs

1//! 系を追跡する解析を、解析のプラグイン(`lensbench_core::plugin`)として登録する同梱の crate。
2//!
3//! 計算は core(`crate::analysis`・`crate::psf`)のまま、名前・設定・配列の約束で包む。
4//! 結果は core の関数を直接呼んだ値とビット一致する。どれも入力は `field`(数 1 つなら視野の番号(1 始まり)、
5//! 2 個なら正規化視野 (hx, hy))で、系は `Context` で受け取る。`wave` は波長の番号(1 始まり、省けば全波長の
6//! 重み付き。wavefront・zernike は省けば主波長)。
7//!
8//! | 名前 | 設定 | 出力 |
9//! |---|---|---|
10//! | `spot` | `wave`・`rings`(6) | `x`・`y`・`weight`・`wave`・`centroid`・`chief`・`rms_centroid`・`rms_chief`・`geo` |
11//! | `wavefront` | `wave`・`n`(64)・`ref_primary`(0) | `p`・`w`((n, n)、外は NaN)・`pv`・`rms` |
12//! | `zernike` | `wave`・`kind`(standard)・`terms`(37)・`n`(64)・`ref_primary`(0) | `coef`・`pv`・`pv_centroid`・`rms_fit`・`max_fit`・`rms_chief`・`rms_centroid`・`variance`・`strehl` |
13//! | `mtf` | `wave`・`freqs`(省けば遮断周波数の 0〜0.95 を 21 点)・`n`・`method`(auto・interp・direct・fft) | `freqs`・`tan`・`sag`・`cutoff` |
14//! | `psf` | `wave`・`pupil`(自動)・`image`(128)・`pixel`・`plane`(image・chief) | `x`・`y`・`i`((image, image))・`center`・`pixel`・`peak`・`pupil`・`phase_step`・`enclosed` |
15//! | `rms` | `wave`・`rings`(6)・`reference`(centroid・chief) | `spot`・`spot_x`・`spot_y`・`wfe`・`strehl` |
16//! | `huygens_psf` | `wave`・`pupil`(自動)・`image`(128)・`pixel` | psf と同じ(x・y は像面の局所座標の中心からの差) |
17//! | `huygens_mtf` | `wave`・`freqs`(省けば mtf と同じ既定)・`pupil`(自動)・`image`(128)・`pixel` | `freqs`・`tan`・`sag`・`cutoff` |
18//! | `geo_mtf` | `wave`・`freqs`(省けば mtf と同じ既定)・`n`(128)・`diff_limit`(0) | `freqs`・`tan`・`sag`・`cutoff` |
19//! | `pop` | `surface`(必須)・`wave`・`dist` か `to`・`method`(auto・fresnel・angular・direct)・`rays`(65)・`n`(256)・`half`・`aperture`(1)・`out_n`・`out_half`・`out_center`(2 個) | 出力の場 `u`(complex (ny, nx)、パイロットを除く)・`dx`・`dy`・`center`・`pilot`(ax・ay・curv)・`power`・`peak`・`centroid`・`rms_width`・`distance`・`wavelength`・`index`・`kernel_step`・`fresnel_error`、入力の場 `input_u`・`input_dx`・`input_dy`・`input_center` |
20//! | `interferogram` | `wave`・`n`(64)・`beam1`(1)・`beam2`(2、0 で参照球)・`scale`(1)・`xtilt`・`ytilt`(0) | `p`・`delta`・`intensity`((n, n)、外は NaN)・`pv`・`rms` |
21//! | `ghost` | `first`(1)・`last`(省けば像面) | 組ごとの `a`・`b`・`marginal_y`・`marginal_u`・`focus`(無限遠は inf)・`wfno`・`intensity`(求まらなければ NaN) |
22//!
23//! `interferogram`(単色の干渉縞)の光束は系の多重構成の構成(`System::config`、構成が 1 つなら 1 だけ)。
24//! `pop` は系の視野で入力の場を作り、`ghost` は視野を使わない(入力なし)。`ghost` の膜は `Context` の膜(なければ
25//! 系の膜ファイル)を使う。
26
27use lensbench_core::Waves;
28use std::sync::Arc;
29
30use crate::analysis::{self, MtfMethod, ZernKind};
31use crate::ghost;
32use crate::huygens::{self, HuygensDevice, HuygensOpts};
33use crate::interference::{self, PupilOpts};
34use crate::pop::{self, OutGrid, PopMethod, RayBeamOpts};
35use crate::psf::{self, PsfOpts, PsfPlane};
36use crate::sweep::{self, RmsOpts, RmsRef};
37use lensbench_core::coating::Coatings;
38use lensbench_core::plugin::{
39    check_wave, field_sel, Array, ArrayReader, Arrays, Config, ConfigReader, Context, Instance,
40    Kind, OutputSpec, ParamSpec, ParamType, Plugin, Registry, Spec, Value,
41};
42use lensbench_core::{invalid, FieldSel, Result, System};
43
44/// 同梱の解析を `reg` に登録する
45pub fn register(reg: &mut Registry) {
46    for p in [
47        Analysis::Spot,
48        Analysis::Wavefront,
49        Analysis::Zernike,
50        Analysis::Mtf,
51        Analysis::Psf,
52        Analysis::Rms,
53        Analysis::GeoMtf,
54        Analysis::HuygensPsf,
55        Analysis::HuygensMtf,
56        Analysis::Pop,
57        Analysis::Ghost,
58        Analysis::Interferogram,
59    ] {
60        reg.register(Arc::new(p));
61    }
62}
63
64/// 同梱の解析の種類
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum Analysis {
67    Spot,
68    Wavefront,
69    Zernike,
70    Mtf,
71    Psf,
72    Rms,
73    GeoMtf,
74    HuygensPsf,
75    HuygensMtf,
76    Pop,
77    Ghost,
78    Interferogram,
79}
80
81/// 設定の決まった解析
82#[derive(Debug, Clone)]
83pub enum Prepared {
84    Spot {
85        wave: Option<usize>,
86        rings: usize,
87    },
88    Wavefront {
89        wave: Option<usize>,
90        n: usize,
91        ref_primary: bool,
92    },
93    Zernike {
94        wave: Option<usize>,
95        kind: ZernKind,
96        terms: usize,
97        n: usize,
98        ref_primary: bool,
99    },
100    Mtf {
101        wave: Option<usize>,
102        freqs: Option<Vec<f64>>,
103        n: Option<usize>,
104        method: MtfMethod,
105    },
106    Psf {
107        wave: Option<usize>,
108        opts: PsfOpts,
109    },
110    Rms {
111        wave: Option<usize>,
112        opts: RmsOpts,
113    },
114    GeoMtf {
115        wave: Option<usize>,
116        freqs: Option<Vec<f64>>,
117        n: usize,
118        diff_limit: bool,
119    },
120    HuygensPsf {
121        wave: Option<usize>,
122        opts: HuygensOpts,
123    },
124    HuygensMtf {
125        wave: Option<usize>,
126        freqs: Option<Vec<f64>>,
127        opts: HuygensOpts,
128    },
129    Pop {
130        wave: Option<usize>,
131        surface: usize,
132        dist: Option<f64>,
133        to: Option<usize>,
134        method: PopMethod,
135        opts: RayBeamOpts,
136        out: OutGrid,
137    },
138    Ghost {
139        first: usize,
140        last: Option<usize>,
141    },
142    Interferogram {
143        wave: Option<usize>,
144        beam1: usize,
145        beam2: usize,
146        opts: PupilOpts,
147    },
148}
149
150fn s2(a: &str, b: &str) -> (String, String) {
151    (a.to_string(), b.to_string())
152}
153
154/// 設定の項目の定義(既定値は登録簿に無い項目だけここに書く。登録簿にある項目は [`Plugin::params`] が埋める)
155impl Analysis {
156    /// 登録簿([`crate::registry::Analyses::builtin`])の同じ解析の名前(無ければ None)
157    fn registry_name(&self) -> Option<&'static str> {
158        match self {
159            Analysis::Spot => Some("spot"),
160            Analysis::Wavefront => Some("wavefront"),
161            Analysis::Zernike => Some("zernike"),
162            Analysis::Mtf => Some("mtf"),
163            Analysis::Psf | Analysis::HuygensPsf => Some("psf"),
164            Analysis::Rms => Some("rms"),
165            Analysis::GeoMtf => Some("geo-mtf"),
166            Analysis::HuygensMtf => Some("huygens-mtf"),
167            Analysis::Ghost => Some("ghost"),
168            Analysis::Pop | Analysis::Interferogram => None,
169        }
170    }
171
172    fn own_params(&self) -> Vec<ParamSpec> {
173        use ParamType::{Choice, Count, Flag, Num, Nums};
174        let p = ParamSpec::new;
175        let n = |x: f64| Some(Value::Num(x));
176        let b = |x: bool| Some(Value::Bool(x));
177        let st = |x: &str| Some(Value::Str(x.into()));
178        // 既定値は登録簿の同じ項目から([`Plugin::params`] が埋める)
179        let reg = || None;
180        let ch = |v: &[&str]| Choice(v.iter().map(|x| x.to_string()).collect());
181        let wave = || {
182            p(
183                "wave",
184                Count,
185                None,
186                "",
187                "Wavelength number (from 1; polychromatic or primary wavelength if omitted)",
188            )
189        };
190        let freqs = || {
191            p(
192                "freqs",
193                Nums { len: None },
194                None,
195                "cycles/mm",
196                "Frequencies (21 points from 0 to 0.95 of the cutoff if omitted)",
197            )
198        };
199        let refp = || {
200            p(
201                "ref_primary",
202                Flag,
203                b(false),
204                "",
205                "Reference to the chief ray of the primary wavelength (false: the chief ray of that wavelength, as in the CLI and OpticStudio)",
206            )
207        };
208        let pupil = || {
209            p(
210                "pupil",
211                Count,
212                None,
213                "",
214                "Side of the pupil grid (automatic if omitted: phase difference between neighboring samples at most π/2)",
215            )
216        };
217        let image = || p("image", Count, reg(), "", "Side of the image grid");
218        let pixel = || {
219            p(
220                "pixel",
221                Num,
222                None,
223                "mm",
224                "Spacing of the image grid (automatic if omitted)",
225            )
226        };
227        let exact = || {
228            p("exact", Flag, b(false), "", "Sum every pupil sample exactly at every image point (several times slower). By default each pupil sample's phase and amplitude are approximated by a quadratic over small blocks of the image grid; the block size is chosen so that the phase differs from the exact value by at most 1e-6 rad, checked on the corner and center blocks of the grid (the intensity typically agrees with the exact sum to 1e-7 of the unaberrated peak)")
229        };
230        let device = || {
231            p("device", ch(&["auto", "cpu", "gpu"]), st("auto"), "", "Where to compute the Huygens sum: auto (default; a GPU if one is present, otherwise the CPU), cpu, or gpu (use the GPU path even on a software adapter; falls back to the CPU with a warning). The GPU sums in single precision (the intensity agrees with the exact sum to about 5e-7 of the unaberrated peak). Not used with exact")
232        };
233        match self {
234            Analysis::Spot => vec![
235                wave(),
236                p(
237                    "rings",
238                    Count,
239                    reg(),
240                    "",
241                    "Number of rings of the Gaussian quadrature",
242                ),
243            ],
244            Analysis::Wavefront => vec![wave(), p("n", Count, reg(), "", "Grid side"), refp()],
245            Analysis::Zernike => vec![
246                wave(),
247                p(
248                    "kind",
249                    ch(&["standard", "fringe"]),
250                    reg(),
251                    "",
252                    "Ordering",
253                ),
254                p("terms", Count, reg(), "", "Number of terms"),
255                p("n", Count, reg(), "", "Grid side"),
256                refp(),
257            ],
258            Analysis::Mtf => vec![
259                wave(),
260                freqs(),
261                p(
262                    "n",
263                    Count,
264                    None,
265                    "",
266                    "Side of the pupil grid (automatic if omitted)",
267                ),
268                p(
269                    "method",
270                    ch(&["auto", "interp", "direct", "fft"]),
271                    reg(),
272                    "",
273                    "Calculation method",
274                ),
275            ],
276            Analysis::Psf => vec![
277                wave(),
278                pupil(),
279                image(),
280                pixel(),
281                p(
282                    "plane",
283                    ch(&["image", "chief"]),
284                    reg(),
285                    "",
286                    "Plane of the image grid (image: the image surface; chief: perpendicular to the chief ray, as in OpticStudio's FFT PSF)",
287                ),
288            ],
289            Analysis::HuygensPsf => vec![wave(), pupil(), image(), pixel(), exact(), device()],
290            Analysis::Rms => vec![
291                wave(),
292                p(
293                    "rings",
294                    Count,
295                    reg(),
296                    "",
297                    "Number of rings of the Gaussian quadrature",
298                ),
299                p(
300                    "reference",
301                    ch(&["centroid", "chief"]),
302                    reg(),
303                    "",
304                    "Reference",
305                ),
306            ],
307            Analysis::GeoMtf => vec![
308                wave(),
309                freqs(),
310                p("n", Count, reg(), "", "Number of quadrature points"),
311                p(
312                    "diff_limit",
313                    Flag,
314                    reg(),
315                    "",
316                    "Multiply by the diffraction limit",
317                ),
318            ],
319            Analysis::HuygensMtf => vec![wave(), freqs(), pupil(), image(), pixel(), exact(), device()],
320            Analysis::Pop => vec![
321                wave(),
322                p(
323                    "surface",
324                    Count,
325                    None,
326                    "",
327                    "Surface to build the field on (required)",
328                ),
329                p(
330                    "dist",
331                    Num,
332                    None,
333                    "mm",
334                    "Propagation distance (either this or to)",
335                ),
336                p(
337                    "to",
338                    Count,
339                    None,
340                    "",
341                    "Surface to propagate to (surface + 1 if omitted)",
342                ),
343                p(
344                    "method",
345                    ch(&["auto", "fresnel", "angular", "direct"]),
346                    st("auto"),
347                    "",
348                    "Calculation method",
349                ),
350                p(
351                    "rays",
352                    Count,
353                    n(65.0),
354                    "",
355                    "Number of rays on a side of the pupil grid",
356                ),
357                p("n", Count, n(256.0), "", "Side of the input grid"),
358                p(
359                    "half",
360                    Num,
361                    None,
362                    "mm",
363                    "Half width of the input grid (automatic if omitted)",
364                ),
365                p(
366                    "aperture",
367                    Flag,
368                    b(true),
369                    "",
370                    "Clip by the surface aperture",
371                ),
372                p("out_n", Count, None, "", "Side of the output grid"),
373                p("out_half", Num, None, "mm", "Half width of the output grid"),
374                p(
375                    "out_center",
376                    Nums { len: Some(2) },
377                    None,
378                    "mm",
379                    "Center of the output grid (x, y)",
380                ),
381            ],
382            Analysis::Ghost => vec![
383                p("first", Count, reg(), "", "First surface"),
384                p(
385                    "last",
386                    Count,
387                    None,
388                    "",
389                    "Last surface (image surface if omitted)",
390                ),
391            ],
392            Analysis::Interferogram => vec![
393                wave(),
394                p("n", Count, n(64.0), "", "Grid side"),
395                p("beam1", Count, n(1.0), "", "Configuration of beam 1"),
396                p(
397                    "beam2",
398                    Count,
399                    n(2.0),
400                    "",
401                    "Configuration of beam 2 (0 for the reference sphere)",
402                ),
403                p(
404                    "scale",
405                    Num,
406                    n(1.0),
407                    "",
408                    "Factor applied to the OPD difference (2 for double pass)",
409                ),
410                p(
411                    "xtilt",
412                    Num,
413                    n(0.0),
414                    "",
415                    "Number of tilt fringes (per pupil diameter)",
416                ),
417                p(
418                    "ytilt",
419                    Num,
420                    n(0.0),
421                    "",
422                    "Number of tilt fringes (per pupil diameter)",
423                ),
424            ],
425        }
426    }
427}
428
429/// 登録簿の既定値(JSON)→ プラグインの設定の値(null は None)
430fn json_value(j: &serde_json::Value) -> Option<Value> {
431    use serde_json::Value as J;
432    match j {
433        J::Number(n) => n.as_f64().map(Value::Num),
434        J::Bool(b) => Some(Value::Bool(*b)),
435        J::String(x) => Some(Value::Str(x.clone())),
436        J::Array(a) => a
437            .iter()
438            .map(J::as_f64)
439            .collect::<Option<Vec<_>>>()
440            .map(Value::Nums),
441        _ => None,
442    }
443}
444
445/// 設定の既定値([`Plugin::params`] の)。prepare で省いた項目に使う
446struct Defaults(Vec<ParamSpec>);
447
448impl Defaults {
449    fn get(&self, k: &str) -> Result<&Value> {
450        match self
451            .0
452            .iter()
453            .find(|p| p.name == k)
454            .and_then(|p| p.default.as_ref())
455        {
456            Some(v) => Ok(v),
457            None => invalid!("internal: plugin setting {k} has no default"),
458        }
459    }
460    fn count(&self, k: &str) -> Result<usize> {
461        match self.get(k)? {
462            Value::Num(x) => Ok(*x as usize),
463            v => invalid!("internal: default of plugin setting {k} is {v:?}"),
464        }
465    }
466    fn num(&self, k: &str) -> Result<f64> {
467        match self.get(k)? {
468            Value::Num(x) => Ok(*x),
469            v => invalid!("internal: default of plugin setting {k} is {v:?}"),
470        }
471    }
472    fn flag(&self, k: &str) -> Result<bool> {
473        match self.get(k)? {
474            Value::Bool(b) => Ok(*b),
475            v => invalid!("internal: default of plugin setting {k} is {v:?}"),
476        }
477    }
478    fn str(&self, k: &str) -> Result<&str> {
479        match self.get(k)? {
480            Value::Str(x) => Ok(x),
481            v => invalid!("internal: default of plugin setting {k} is {v:?}"),
482        }
483    }
484}
485
486impl Plugin for Analysis {
487    fn name(&self) -> &str {
488        match self {
489            Analysis::Spot => "spot",
490            Analysis::Wavefront => "wavefront",
491            Analysis::Zernike => "zernike",
492            Analysis::Mtf => "mtf",
493            Analysis::Psf => "psf",
494            Analysis::Rms => "rms",
495            Analysis::GeoMtf => "geo_mtf",
496            Analysis::HuygensPsf => "huygens_psf",
497            Analysis::HuygensMtf => "huygens_mtf",
498            Analysis::Pop => "pop",
499            Analysis::Ghost => "ghost",
500            Analysis::Interferogram => "interferogram",
501        }
502    }
503
504    fn kind(&self) -> Kind {
505        Kind::Analysis
506    }
507
508    fn spec(&self) -> Spec {
509        let (doc, outputs) = match self {
510            Analysis::Spot => (
511                "Spot (RMS and GEO radius)",
512                vec![
513                    OutputSpec::from_doc("x", "Ray position [mm]"),
514                    OutputSpec::from_doc("y", "Ray position [mm]"),
515                    OutputSpec::from_doc("weight", "Ray weight"),
516                    OutputSpec::from_doc("wave", "Wavelength number of the ray (from 1)"),
517                    OutputSpec::from_doc("centroid", "(2,) [mm]"),
518                    OutputSpec::from_doc("chief", "(2,) [mm]"),
519                    OutputSpec::from_doc("rms_centroid", "[mm]"),
520                    OutputSpec::from_doc("rms_chief", "[mm]"),
521                    OutputSpec::from_doc("geo", "[mm]"),
522                ],
523            ),
524            Analysis::Wavefront => (
525                "Wavefront error (OPD relative to the chief ray [waves])",
526                vec![
527                    OutputSpec::from_doc("p", "Pupil coordinates of the grid (n,)"),
528                    OutputSpec::from_doc("w", "OPD, NaN outside (n, n) [waves]"),
529                    OutputSpec::from_doc("pv", "[waves]"),
530                    OutputSpec::from_doc("rms", "[waves]"),
531                ],
532            ),
533            Analysis::Zernike => (
534                "Zernike coefficients [waves]",
535                vec![
536                    OutputSpec::from_doc("coef", "Coefficients [waves]"),
537                    OutputSpec::from_doc("pv", "[waves]"),
538                    OutputSpec::from_doc("pv_centroid", "[waves]"),
539                    OutputSpec::from_doc("rms_fit", "[waves]"),
540                    OutputSpec::from_doc("max_fit", "[waves]"),
541                    OutputSpec::from_doc("rms_chief", "[waves]"),
542                    OutputSpec::from_doc("rms_centroid", "[waves]"),
543                    OutputSpec::from_doc("variance", "[waves²]"),
544                    OutputSpec::from_doc("strehl", "Strehl ratio"),
545                ],
546            ),
547            Analysis::Mtf => (
548                "Diffraction MTF",
549                vec![
550                    OutputSpec::from_doc("freqs", "[cycles/mm]"),
551                    OutputSpec::from_doc("tan", "Tangential"),
552                    OutputSpec::from_doc("sag", "Sagittal"),
553                    OutputSpec::from_doc("cutoff", "tangential and sagittal (2,) [cycles/mm]"),
554                ],
555            ),
556            Analysis::Psf => (
557                "FFT PSF",
558                vec![
559                    OutputSpec::from_doc("x", "(image,) [mm]"),
560                    OutputSpec::from_doc("y", "(image,) [mm]"),
561                    OutputSpec::from_doc("i", "1 at the center without aberrations (image, image)"),
562                    OutputSpec::from_doc("center", "(2,) [mm]"),
563                    OutputSpec::from_doc("pixel", "(2,) [mm]"),
564                    OutputSpec::from_doc("peak", "Maximum of the grid"),
565                    OutputSpec::from_doc("pupil", "Side of the pupil grid used"),
566                    OutputSpec::from_doc("phase_step", "Largest phase difference between neighboring pupil samples (undersampled above π/2) [rad]"),
567                    OutputSpec::from_doc("enclosed", "Fraction of the energy inside the image grid"),
568                ],
569            ),
570            Analysis::Rms => (
571                "RMS spot radius, wavefront error and Strehl ratio",
572                vec![
573                    OutputSpec::from_doc("spot", "[mm]"),
574                    OutputSpec::from_doc("spot_x", "[mm]"),
575                    OutputSpec::from_doc("spot_y", "[mm]"),
576                    OutputSpec::from_doc("wfe", "[waves]"),
577                    OutputSpec::from_doc("strehl", "Approximate"),
578                ],
579            ),
580            Analysis::GeoMtf => (
581                "Geometric MTF",
582                vec![
583                    OutputSpec::from_doc("freqs", "[cycles/mm]"),
584                    OutputSpec::from_doc("tan", "Tangential"),
585                    OutputSpec::from_doc("sag", "Sagittal"),
586                    OutputSpec::from_doc("cutoff", "tangential and sagittal (2,) [cycles/mm]"),
587                ],
588            ),
589            Analysis::HuygensPsf => (
590                "Huygens PSF (on the image surface, sum of secondary waves from each point of the reference sphere)",
591                vec![
592                    OutputSpec::from_doc("x", "local image x relative to center (image,) [mm]"),
593                    OutputSpec::from_doc("y", "local image y relative to center (image,) [mm]"),
594                    OutputSpec::from_doc("i", "1 at the center without aberrations (image, image)"),
595                    OutputSpec::from_doc("center", "(2,) [mm]"),
596                    OutputSpec::from_doc("pixel", "(2,) [mm]"),
597                    OutputSpec::from_doc("peak", "Maximum of the grid"),
598                    OutputSpec::from_doc("pupil", "Side of the pupil grid used"),
599                    OutputSpec::from_doc("phase_step", "Largest phase difference between neighboring pupil samples (undersampled above π/2) [rad]"),
600                    OutputSpec::from_doc("enclosed", "Fraction of the energy inside the image grid"),
601                ],
602            ),
603            Analysis::HuygensMtf => (
604                "Huygens MTF (Fourier transform of the Huygens PSF)",
605                vec![
606                    OutputSpec::from_doc("freqs", "[cycles/mm]"),
607                    OutputSpec::from_doc("tan", "Tangential (image y)"),
608                    OutputSpec::from_doc("sag", "Sagittal (image x)"),
609                    OutputSpec::from_doc("cutoff", "tangential and sagittal (2,) [cycles/mm]"),
610                ],
611            ),
612            Analysis::Pop => (
613                "Simple POP (build the field after a surface and propagate it over a distance or to a surface)",
614                vec![
615                    OutputSpec::from_doc("u", "Output field (without the pilot beam) complex (ny, nx)"),
616                    OutputSpec::from_doc("dx", "[mm]"),
617                    OutputSpec::from_doc("dy", "[mm]"),
618                    OutputSpec::from_doc("center", "(2,) [mm]"),
619                    OutputSpec::from_doc("pilot", "(ax, ay, curv)"),
620                    OutputSpec::from_doc("power", "Output power"),
621                    OutputSpec::from_doc("peak", "Output peak intensity"),
622                    OutputSpec::from_doc("centroid", "(2,) [mm]"),
623                    OutputSpec::from_doc("rms_width", "[mm]"),
624                    OutputSpec::from_doc("distance", "Propagation distance [mm]"),
625                    OutputSpec::from_doc("wavelength", "[mm]"),
626                    OutputSpec::from_doc("index", "Refractive index of the medium"),
627                    OutputSpec::from_doc("kernel_step", "Phase difference of the kernel between samples [rad]"),
628                    OutputSpec::from_doc("fresnel_error", "Phase dropped by the Fresnel approximation [rad]"),
629                    OutputSpec::from_doc("input_u", "Input field complex (ny, nx)"),
630                    OutputSpec::from_doc("input_dx", "[mm]"),
631                    OutputSpec::from_doc("input_dy", "[mm]"),
632                    OutputSpec::from_doc("input_center", "(2,) [mm]"),
633                ],
634            ),
635            Analysis::Ghost => (
636                "List of double-bounce ghosts (paraxial quantities and intensity ratio)",
637                vec![
638                    OutputSpec::from_doc("a", "Surface of the first reflection"),
639                    OutputSpec::from_doc("b", "Surface of the second reflection"),
640                    OutputSpec::from_doc("marginal_y", "[mm]"),
641                    OutputSpec::from_doc("marginal_u", ""),
642                    OutputSpec::from_doc("focus", "(inf at infinity) [mm]"),
643                    OutputSpec::from_doc("wfno", ""),
644                    OutputSpec::from_doc("intensity", "Intensity ratio (NaN if not found)"),
645                ],
646            ),
647            Analysis::Interferogram => (
648                "Monochromatic interferogram (on the pupil, like OpticStudio's Interferogram): Δ = scale·(W1 − W2) + (xtilt·px + ytilt·py)/2",
649                vec![
650                    OutputSpec::from_doc("p", "Pupil coordinates of the grid (n,)"),
651                    OutputSpec::from_doc("delta", "Δ, NaN outside (n, n) [waves]"),
652                    OutputSpec::from_doc("intensity", "(1 + cos 2πΔ)/2, NaN outside (n, n)"),
653                    OutputSpec::from_doc("pv", "P-V of scale·(W1 − W2) (tilt removed) [waves]"),
654                    OutputSpec::from_doc("rms", "RMS of scale·(W1 − W2) (tilt removed) [waves]"),
655                ],
656            ),
657        };
658        let inputs = if *self == Analysis::Ghost {
659            Vec::new()
660        } else {
661            vec![s2(
662                "field",
663                "Field number (from 1) or normalized field (2,)",
664            )]
665        };
666        Spec {
667            doc: doc.into(),
668            inputs,
669            outputs,
670            needs_system: true,
671        }
672    }
673
674    /// 設定の項目。登録簿に同じ解析・同じ名前の項目があれば、既定値はそちらから取る(既定値を 1 か所に)
675    fn params(&self) -> Vec<ParamSpec> {
676        let mut v = self.own_params();
677        let Some(a) = self
678            .registry_name()
679            .and_then(|n| crate::registry::Analyses::builtin().get(n))
680        else {
681            return v;
682        };
683        let reg: std::collections::BTreeMap<String, serde_json::Value> = a
684            .params()
685            .into_iter()
686            .map(|x| (x.name, x.default))
687            .collect();
688        for s in &mut v {
689            if let Some(d) = reg.get(&s.name).and_then(json_value) {
690                s.default = Some(d);
691            }
692        }
693        v
694    }
695
696    fn prepare(&self, config: &Config) -> Result<Box<dyn Instance>> {
697        let mut r = ConfigReader::new(config);
698        // 省いた項目は設定の項目の既定値(登録簿から取ったものも)
699        let d = Defaults(self.params());
700        let wave = r.wave("wave")?;
701        let p = match self {
702            Analysis::Spot => Prepared::Spot {
703                wave,
704                rings: r.count("rings", d.count("rings")?)?,
705            },
706            Analysis::Wavefront => Prepared::Wavefront {
707                wave,
708                n: r.count("n", d.count("n")?)?,
709                ref_primary: r.flag("ref_primary", d.flag("ref_primary")?)?,
710            },
711            Analysis::Zernike => Prepared::Zernike {
712                wave,
713                kind: zern_kind(&r.str("kind", d.str("kind")?)?)?,
714                terms: r.count("terms", d.count("terms")?)?,
715                n: r.count("n", d.count("n")?)?,
716                ref_primary: r.flag("ref_primary", d.flag("ref_primary")?)?,
717            },
718            Analysis::Mtf => Prepared::Mtf {
719                wave,
720                freqs: r.nums("freqs")?,
721                n: r.opt_count("n")?,
722                method: match r.str("method", d.str("method")?)?.as_str() {
723                    "auto" => MtfMethod::Auto,
724                    "interp" => MtfMethod::Interp,
725                    "direct" => MtfMethod::Direct,
726                    "fft" => MtfMethod::Fft,
727                    x => invalid!("setting method must be auto, interp, direct or fft ({x})"),
728                },
729            },
730            Analysis::Psf => {
731                let pixel = r.opt_num("pixel")?;
732                Prepared::Psf {
733                    wave,
734                    opts: PsfOpts {
735                        pupil: r.opt_count("pupil")?,
736                        image: r.count("image", d.count("image")?)?,
737                        pixel,
738                        plane: match r.str("plane", d.str("plane")?)?.as_str() {
739                            "image" => PsfPlane::Image,
740                            "chief" => PsfPlane::ChiefPerp,
741                            x => invalid!("setting plane must be image or chief ({x})"),
742                        },
743                    },
744                }
745            }
746            Analysis::Rms => Prepared::Rms {
747                wave,
748                opts: RmsOpts {
749                    rings: r.count("rings", d.count("rings")?)?,
750                    reference: match r
751                        .str("reference", d.str("reference")?)?
752                        .to_ascii_lowercase()
753                        .as_str()
754                    {
755                        "centroid" => RmsRef::Centroid,
756                        "chief" => RmsRef::Chief,
757                        x => invalid!("setting reference must be centroid or chief ({x})"),
758                    },
759                    ..Default::default()
760                },
761            },
762            Analysis::GeoMtf => Prepared::GeoMtf {
763                wave,
764                freqs: r.nums("freqs")?,
765                n: r.count("n", d.count("n")?)?,
766                diff_limit: r.flag("diff_limit", d.flag("diff_limit")?)?,
767            },
768            Analysis::HuygensPsf | Analysis::HuygensMtf => {
769                let pixel = r.opt_num("pixel")?;
770                let opts = HuygensOpts {
771                    pupil: r.opt_count("pupil")?,
772                    image: r.count("image", d.count("image")?)?,
773                    pixel,
774                    exact: r.flag("exact", d.flag("exact")?)?,
775                    device: match r.str("device", d.str("device")?)?.as_str() {
776                        "auto" => HuygensDevice::Auto,
777                        "cpu" => HuygensDevice::Cpu,
778                        "gpu" => HuygensDevice::Gpu,
779                        x => invalid!("setting device must be auto, cpu or gpu ({x})"),
780                    },
781                };
782                if *self == Analysis::HuygensPsf {
783                    Prepared::HuygensPsf { wave, opts }
784                } else {
785                    Prepared::HuygensMtf {
786                        wave,
787                        freqs: r.nums("freqs")?,
788                        opts,
789                    }
790                }
791            }
792            Analysis::Pop => {
793                let Some(surface) = r.opt_count("surface")? else {
794                    invalid!("setting surface (the surface that makes the field) is needed");
795                };
796                let dist = opt_num(&mut r, "dist")?;
797                let to = r.opt_count("to")?;
798                if dist.is_some() && to.is_some() {
799                    invalid!("give only one of the settings dist and to");
800                }
801                let method = match r.str("method", d.str("method")?)?.as_str() {
802                    "auto" => PopMethod::Auto,
803                    "fresnel" => PopMethod::Fresnel,
804                    "angular" => PopMethod::Angular,
805                    "direct" => PopMethod::Direct,
806                    x => invalid!("setting method must be auto, fresnel, angular or direct ({x})"),
807                };
808                let opts = RayBeamOpts {
809                    rays: r.count("rays", d.count("rays")?)?,
810                    n: r.count("n", d.count("n")?)?,
811                    half: opt_num(&mut r, "half")?,
812                    aperture: r.flag("aperture", d.flag("aperture")?)?,
813                    overfill: None,
814                };
815                let out = OutGrid {
816                    n: r.opt_count("out_n")?.map(|v| (v, v)),
817                    half: opt_num(&mut r, "out_half")?.map(|v| (v, v)),
818                    center: match r.nums("out_center")? {
819                        None => None,
820                        Some(v) if v.len() == 2 => Some((v[0], v[1])),
821                        Some(v) => {
822                            invalid!("setting out_center needs 2 values ({} values)", v.len())
823                        }
824                    },
825                };
826                Prepared::Pop {
827                    wave,
828                    surface,
829                    dist,
830                    to,
831                    method,
832                    opts,
833                    out,
834                }
835            }
836            Analysis::Ghost => {
837                if wave.is_some() {
838                    invalid!("wave can't be used with ghost (computed at the primary wavelength)");
839                }
840                Prepared::Ghost {
841                    first: r.count("first", d.count("first")?)?,
842                    last: r.opt_count("last")?,
843                }
844            }
845            Analysis::Interferogram => {
846                let beam1 = r.count("beam1", d.count("beam1")?)?;
847                if beam1 == 0 {
848                    invalid!("setting beam1 must be 1 or more (a configuration number)");
849                }
850                Prepared::Interferogram {
851                    wave,
852                    beam1,
853                    beam2: r.count("beam2", d.count("beam2")?)?,
854                    opts: PupilOpts {
855                        n: r.count("n", d.count("n")?)?,
856                        scale: r.num("scale", d.num("scale")?)?,
857                        xtilt: r.num("xtilt", d.num("xtilt")?)?,
858                        ytilt: r.num("ytilt", d.num("ytilt")?)?,
859                    },
860                }
861            }
862        };
863        r.finish()?;
864        Ok(Box::new(p))
865    }
866}
867
868fn opt_num(r: &mut ConfigReader<'_>, key: &str) -> Result<Option<f64>> {
869    r.opt_num(key)
870}
871
872fn zern_kind(s: &str) -> Result<ZernKind> {
873    match s.to_ascii_lowercase().as_str() {
874        "standard" => Ok(ZernKind::Standard),
875        "fringe" => Ok(ZernKind::Fringe),
876        x => invalid!("setting kind must be standard or fringe ({x})"),
877    }
878}
879
880fn v1(v: Vec<f64>) -> Result<Array> {
881    Array::f64(vec![v.len()], v)
882}
883
884fn out(items: Vec<(&str, Array)>) -> Arrays {
885    items.into_iter().map(|(k, v)| (k.to_string(), v)).collect()
886}
887
888impl Prepared {
889    fn wave(&self) -> Option<usize> {
890        match self {
891            Prepared::Spot { wave, .. }
892            | Prepared::Wavefront { wave, .. }
893            | Prepared::Zernike { wave, .. }
894            | Prepared::Mtf { wave, .. }
895            | Prepared::Psf { wave, .. }
896            | Prepared::Rms { wave, .. }
897            | Prepared::GeoMtf { wave, .. }
898            | Prepared::HuygensPsf { wave, .. }
899            | Prepared::HuygensMtf { wave, .. }
900            | Prepared::Pop { wave, .. }
901            | Prepared::Interferogram { wave, .. } => *wave,
902            Prepared::Ghost { .. } => None,
903        }
904    }
905
906    /// 系と視野で解析する
907    pub fn evaluate(&self, s: &System, f: FieldSel) -> Result<Arrays> {
908        check_wave(s, self.wave())?;
909        Ok(match self {
910            Prepared::Spot { wave, rings } => {
911                let r = analysis::spot(s, f, Waves::all_or(*wave), *rings)?;
912                out(vec![
913                    ("x", v1(r.x)?),
914                    ("y", v1(r.y)?),
915                    ("weight", v1(r.weight)?),
916                    (
917                        "wave",
918                        v1(r.wave.iter().map(|&w| (w + 1) as f64).collect())?,
919                    ),
920                    ("centroid", v1(vec![r.centroid.0, r.centroid.1])?),
921                    ("chief", v1(vec![r.chief.0, r.chief.1])?),
922                    ("rms_centroid", Array::scalar(r.rms_centroid)),
923                    ("rms_chief", Array::scalar(r.rms_chief)),
924                    ("geo", Array::scalar(r.geo)),
925                ])
926            }
927            Prepared::Wavefront {
928                wave,
929                n,
930                ref_primary,
931            } => {
932                let r = analysis::wavefront(s, f, *wave, *n, *ref_primary)?;
933                out(vec![
934                    ("p", v1(r.w.x().to_vec())?),
935                    ("w", Array::grid(&r.w)),
936                    ("pv", Array::scalar(r.pv)),
937                    ("rms", Array::scalar(r.rms)),
938                ])
939            }
940            Prepared::Zernike {
941                wave,
942                kind,
943                terms,
944                n,
945                ref_primary,
946            } => {
947                let r = analysis::zernike(s, f, *wave, *kind, *terms, *n, *ref_primary)?;
948                out(vec![
949                    ("coef", v1(r.coef)?),
950                    ("pv", Array::scalar(r.pv)),
951                    ("pv_centroid", Array::scalar(r.pv_centroid)),
952                    ("rms_fit", Array::scalar(r.rms_fit)),
953                    ("max_fit", Array::scalar(r.max_fit)),
954                    ("rms_chief", Array::scalar(r.rms_chief)),
955                    ("rms_centroid", Array::scalar(r.rms_centroid)),
956                    ("variance", Array::scalar(r.variance)),
957                    ("strehl", Array::scalar(r.strehl)),
958                ])
959            }
960            Prepared::Mtf {
961                wave,
962                freqs,
963                n,
964                method,
965            } => {
966                let fs = default_freqs(s, f, *wave, freqs)?;
967                let r = analysis::mtf_with(s, f, Waves::all_or(*wave), *n, &fs, *method)?;
968                out(vec![
969                    ("freqs", v1(r.freqs)?),
970                    ("tan", v1(r.tan)?),
971                    ("sag", v1(r.sag)?),
972                    ("cutoff", v1(vec![r.cutoff.tan, r.cutoff.sag])?),
973                ])
974            }
975            Prepared::Psf { wave, opts } => {
976                let r = psf::psf(s, f, Waves::all_or(*wave), *opts)?;
977                out(vec![
978                    ("x", v1(r.i.x().to_vec())?),
979                    ("y", v1(r.i.y().to_vec())?),
980                    ("i", Array::grid(&r.i)),
981                    ("center", v1(vec![r.center.0, r.center.1])?),
982                    ("pixel", v1(vec![r.pixel.0, r.pixel.1])?),
983                    ("peak", Array::scalar(r.peak)),
984                    ("pupil", Array::scalar(r.pupil as f64)),
985                    ("phase_step", Array::scalar(r.phase_step)),
986                    ("enclosed", Array::scalar(r.enclosed)),
987                ])
988            }
989            Prepared::Rms { wave, opts } => {
990                let r = sweep::rms(s, f, Waves::all_or(*wave), *opts)?;
991                out(vec![
992                    ("spot", Array::scalar(r.spot)),
993                    ("spot_x", Array::scalar(r.spot_x)),
994                    ("spot_y", Array::scalar(r.spot_y)),
995                    ("wfe", Array::scalar(r.wfe)),
996                    ("strehl", Array::scalar(r.strehl)),
997                ])
998            }
999            Prepared::GeoMtf {
1000                wave,
1001                freqs,
1002                n,
1003                diff_limit,
1004            } => {
1005                let fs = default_freqs(s, f, *wave, freqs)?;
1006                let r = psf::geometric_mtf(s, f, Waves::all_or(*wave), *n, &fs, *diff_limit)?;
1007                out(vec![
1008                    ("freqs", v1(r.freqs)?),
1009                    ("tan", v1(r.tan)?),
1010                    ("sag", v1(r.sag)?),
1011                    ("cutoff", v1(vec![r.cutoff.tan, r.cutoff.sag])?),
1012                ])
1013            }
1014            Prepared::HuygensPsf { wave, opts } => {
1015                let r = huygens::huygens_psf(s, f, Waves::all_or(*wave), *opts)?;
1016                out(vec![
1017                    ("x", v1(r.i.x().to_vec())?),
1018                    ("y", v1(r.i.y().to_vec())?),
1019                    ("i", Array::grid(&r.i)),
1020                    ("center", v1(vec![r.center.0, r.center.1])?),
1021                    ("pixel", v1(vec![r.pixel.0, r.pixel.1])?),
1022                    ("peak", Array::scalar(r.peak)),
1023                    ("pupil", Array::scalar(r.pupil as f64)),
1024                    ("phase_step", Array::scalar(r.phase_step)),
1025                    ("enclosed", Array::scalar(r.enclosed)),
1026                ])
1027            }
1028            Prepared::HuygensMtf { wave, freqs, opts } => {
1029                let fs = default_freqs(s, f, *wave, freqs)?;
1030                let r = huygens::huygens_mtf(s, f, Waves::all_or(*wave), *opts, &fs)?;
1031                out(vec![
1032                    ("freqs", v1(r.freqs)?),
1033                    ("tan", v1(r.tan)?),
1034                    ("sag", v1(r.sag)?),
1035                    ("cutoff", v1(vec![r.cutoff.tan, r.cutoff.sag])?),
1036                ])
1037            }
1038            Prepared::Pop {
1039                wave,
1040                surface,
1041                dist,
1042                to,
1043                method,
1044                opts,
1045                out: grid,
1046            } => {
1047                let rb = pop::beam_from_rays(s, f, *wave, *surface, opts)?;
1048                let b = &rb.beam;
1049                let d = match dist {
1050                    Some(d) => *d,
1051                    None => pop::distance_to(s, *surface, to.unwrap_or(surface + 1), b.dir)?,
1052                };
1053                let p = pop::propagate(b, d, *method, *grid)?;
1054                let o = &p.beam;
1055                let (cx, cy) = o.centroid();
1056                out(vec![
1057                    ("u", Array::grid(&o.grid())),
1058                    ("dx", Array::scalar(o.dx)),
1059                    ("dy", Array::scalar(o.dy)),
1060                    ("center", v1(vec![o.x0, o.y0])?),
1061                    ("pilot", v1(vec![o.pilot.ax, o.pilot.ay, o.pilot.curv])?),
1062                    ("power", Array::scalar(o.power())),
1063                    ("peak", Array::scalar(o.peak())),
1064                    ("centroid", v1(vec![cx, cy])?),
1065                    ("rms_width", Array::scalar(o.rms_width())),
1066                    ("distance", Array::scalar(d)),
1067                    ("wavelength", Array::scalar(b.wl)),
1068                    ("index", Array::scalar(b.index)),
1069                    ("kernel_step", Array::scalar(p.kernel_step)),
1070                    ("fresnel_error", Array::scalar(p.fresnel_error)),
1071                    ("input_u", Array::grid(&b.grid())),
1072                    ("input_dx", Array::scalar(b.dx)),
1073                    ("input_dy", Array::scalar(b.dy)),
1074                    ("input_center", v1(vec![b.x0, b.y0])?),
1075                ])
1076            }
1077            Prepared::Interferogram {
1078                wave,
1079                beam1,
1080                beam2,
1081                opts,
1082            } => {
1083                let s1 = s.config(*beam1)?;
1084                let s2 = if *beam2 == 0 {
1085                    None
1086                } else {
1087                    Some(s.config(*beam2)?)
1088                };
1089                let r = interference::interferogram(&s1, s2.as_ref(), f, *wave, opts)?;
1090                out(vec![
1091                    ("p", v1(r.delta.x().to_vec())?),
1092                    ("delta", Array::grid(&r.delta)),
1093                    ("intensity", Array::grid(&r.intensity)),
1094                    ("pv", Array::scalar(r.pv)),
1095                    ("rms", Array::scalar(r.rms)),
1096                ])
1097            }
1098            Prepared::Ghost { .. } => invalid!("ghost doesn't use fields"),
1099        })
1100    }
1101
1102    /// ghost: first..=last の面の全部の組
1103    fn ghost(&self, s: &System, coat: Option<&Coatings>) -> Result<Arrays> {
1104        let Prepared::Ghost { first, last } = self else {
1105            invalid!("not a ghost");
1106        };
1107        let last = last.unwrap_or(s.image());
1108        let own;
1109        let co = match coat {
1110            Some(c) => c,
1111            None => {
1112                own = Coatings::for_system(s)?;
1113                &own
1114            }
1115        };
1116        let v = ghost::survey(s, *first, last, co)?;
1117        let col = |f: &dyn Fn(&ghost::GhostInfo) -> f64| v1(v.iter().map(f).collect());
1118        Ok(out(vec![
1119            ("a", col(&|g| g.par.a as f64)?),
1120            ("b", col(&|g| g.par.b as f64)?),
1121            ("marginal_y", col(&|g| g.par.marginal_y)?),
1122            ("marginal_u", col(&|g| g.par.marginal_u)?),
1123            ("focus", col(&|g| g.par.focus)?),
1124            ("wfno", col(&|g| g.par.wfno)?),
1125            (
1126                "intensity",
1127                col(&|g| g.intensity.as_ref().copied().unwrap_or(f64::NAN))?,
1128            ),
1129        ]))
1130    }
1131}
1132
1133/// 周波数(省けば CLI の mtf と同じ既定: 遮断周波数の 0〜0.95 を 21 点)
1134fn default_freqs(
1135    s: &System,
1136    f: FieldSel,
1137    wave: Option<usize>,
1138    freqs: &Option<Vec<f64>>,
1139) -> Result<Vec<f64>> {
1140    Ok(match freqs {
1141        Some(v) => v.clone(),
1142        None => {
1143            let c = analysis::mtf_cutoff(s, f, wave.unwrap_or(s.primary))?.min();
1144            (0..=20).map(|k| 0.95 * c * k as f64 / 20.0).collect()
1145        }
1146    })
1147}
1148
1149impl Instance for Prepared {
1150    fn run(&self, ctx: &Context<'_>, inputs: &Arrays) -> Result<Arrays> {
1151        let s = ctx.system()?;
1152        let mut r = ArrayReader::new(inputs);
1153        if matches!(self, Prepared::Ghost { .. }) {
1154            r.finish()?;
1155            return self.ghost(s, ctx.coatings);
1156        }
1157        let f = field_sel(s, r.req("field")?)?;
1158        r.finish()?;
1159        self.evaluate(s, f)
1160    }
1161}
1162
1163#[cfg(test)]
1164mod defaults_tests {
1165    use super::*;
1166
1167    /// どの同梱プラグインも、prepare が既定値を使う項目に既定値がある(省いた設定で準備できる)。
1168    /// 登録簿にある項目は登録簿の既定値になる
1169    #[test]
1170    fn every_plugin_prepares_with_defaults_from_the_registry() {
1171        let mut r = Registry::new();
1172        register(&mut r);
1173        for p in r.plugins() {
1174            let mut cfg = Config::new();
1175            if p.name() == "pop" {
1176                cfg.insert("surface".into(), Value::Num(1.0));
1177            }
1178            p.prepare(&cfg)
1179                .unwrap_or_else(|e| panic!("{}: {e}", p.name()));
1180        }
1181        let spot = r.get("spot").unwrap().params();
1182        let rings = spot.iter().find(|s| s.name == "rings").unwrap();
1183        assert_eq!(rings.default, Some(Value::Num(6.0)));
1184        let psf = r.get("huygens_psf").unwrap().params();
1185        let image = psf.iter().find(|s| s.name == "image").unwrap();
1186        assert_eq!(image.default, Some(Value::Num(128.0)));
1187    }
1188}