Skip to main content

lensbench_design/
tolerance.rs

1//! モンテカルロ公差の設定の JSON と、結果の JSON。CLI の `tolerance`・serve の `tolerance`・Python の
2//! `System.tolerance` で同じ形を使う。計算は [`crate::montecarlo`]。
3//!
4//! 設定は [`crate::tol_spec::TolSpec`] の型で読む(スキーマ `docs/schema/tolerance.schema.json`、知らないキーは誤り)。
5//!
6//! 設定(すべて省略可。省くと「一般」の公差の組をすべての玉に、ピントを補償子にせず、RMS 波面で 100 回):
7//!
8//! | キー | 意味 |
9//! |---|---|
10//! | `trials` | 試行の数(100)。0 なら感度だけ |
11//! | `seed` | 乱数の種(1)。同じ種なら同じ結果(スレッド数によらない) |
12//! | `dist` | 既定の分布("normal"): "uniform"・"normal"(範囲の端が ±2σ)・"normal:3"・"end"(端の値を半々) |
13//! | `radial` | 偏心・傾き・くさびの x・y を組にして、円の中で引く(false)。`true`・`"uniform"` は円の中で一様、`"normal"`・`"normal:σの数"` は等方の 2 次元正規分布を円で切ったもの(σ = 公差 / σの数、既定 2)。隣り合う x・y の公差(同じ面・玉・群の dx と dy、tx と ty)が対象で、大きさが公差以下になる(x・y 別々では角で √2 倍まで)。組の分布は `dist` によらない |
14//! | `preset` | 玉の既定の公差の組: "commercial"(一般)・"precision"(精密)・"high"(高精度)・"none" |
15//! | `wedge_face` | くさびを入れる面("back"): "back" は玉の後ろの面、"front" は前の面。前・後ろは玉のもとの向き(カタログ・.zmx の向き)で、ブロックを裏返して置いても(`reversed`)、鏡で往復しても同じ面。玉ごとには `lenses` の {"wedge_face": "front"} |
16//! | `catalog` | カタログの玉(プロジェクトのレンズカタログのブロック)はカタログの玉の公差([`catalog_lens_tol`]、`catalog_tols`)を既定にする(true) |
17//! | `catalog_tols` | メーカーごとの公差 {"メーカー": {玉の公差と外径・焦点距離の条件つきの rules}}([`catalog_rule`]。名前は大文字小文字・空白・記号を無視して、ブロックのメーカー名に含まれれば合う。複数が合えばいちばん長い名前。"*" はほか) |
18//! | `lenses` | 玉ごとの上書き {"名前": {玉の公差} か 組の名前 か null(公差なし)}。名前はブロックの id か lens1 … |
19//! | `groups` | 群・ブロックの公差 {"名前": {"decenter", "tilt", "shift"}}。玉 1 つのブロックでは玉の公差(`lenses`)と別に足す(組立の公差。名前は「G1 group decenter x」など) |
20//! | `tols` | 個別の公差の並び(下) |
21//! | `compensators` | 補償子("9.t"・"G1.shift=-1:1"、または {"param", "lo", "hi", "configs"}。configs は効く構成の番号(1 から)の並びで、省くと全構成で同じ値。構成ごとに別の値にするときは構成ごとに 1 つずつ書く) |
22//! | `comp_iters` | 補償子の DLS の反復の上限(10) |
23//! | `merit` | 評価関数: "wavefront"(既定)・"spot"・"none"(terms だけ) |
24//! | `rings`・`ref` | 既定の評価関数の瞳のリング数(3)・基準("centroid"・"chief") |
25//! | `terms` | 足す評価関数の項([`crate::merit`] の形。MTF・近軸量など) |
26//! | `sensitivity` | 公差ごとの感度も求める(true) |
27//! | `percentiles` | 出す百分位([50, 80, 90, 95, 98]) |
28//! | `samples` | 試行ごとのずれと値も返す(false) |
29//!
30//! 玉の公差 {"radius_rel", "focal_rel", "thickness", "wedge", "wedge_face", "dn", "disp", "decenter", "tilt", "space"}
31//! ([`LensTol`]。比・mm・deg。書いた項目だけ既定の組を上書きする)。
32//!
33//! 個別の公差: {"param": "3.t"} か {"params": ["2.r", "3.r"]} に、`pm`(±)か `lo`・`hi`、`relative`(比、false)、
34//! `dist`、`label`、`scale`(パラメータごとにずれに掛ける数の並び。往復する面の厚さのように逆の符号で与えるとき -1)。
35//! "j.nd"・"j.vd" は面 j のガラスの d 線の屈折率・アッベ数のずれ(OpticStudio の TIND・TABB と同じくモデルガラスの式で
36//! 波長ごとの変化を決め、面の dnd・dvd に足す。[`glass_shift`])。
37//!
38//! 鏡の `back` で同じ玉を往復する系では、玉の公差の組は往きと戻りの面に同じ誤差を与える(曲率・くさびは同じ面、
39//! 厚さ・間隔は戻りで逆の符号、偏心・傾きは往復の範囲を持つブロックの動き)。玉の名前はブロックの id。
40//!
41//! 光源の波長のずれは {"param": "wave", "pm": 0.01}(µm。すべての波長を試行ごとに同じだけずらし、全媒質の屈折率が
42//! その波長の値になる)。1 つの波長だけなら "wave1" など(1 から)。
43
44use std::collections::{HashMap, HashSet};
45
46use crate::montecarlo::{
47    self as tolerance, CompMode, Dist, GlassShift, GroupTol, Inverse, InverseTarget, LensTol,
48    McResult, McSpec, Tol,
49};
50use lensbench_analysis::sweep::RmsRef;
51use lensbench_core::catalog::VendorKey;
52use lensbench_core::param::{Kind, Param};
53use lensbench_core::System;
54use lensbench_optim::{DefaultMerit, DlsOpts, Problem, Var};
55use serde_json::{json, Value};
56
57use crate::term_spec::RefName;
58pub use crate::tol_report::ToleranceReport;
59use crate::tol_report::{
60    fin, CompStats, CorrInfo, InverseInfo, InverseTolInfo, Sample, SensInfo, StatsInfo, TermStats,
61    TiltStats, TolInfo,
62};
63use crate::tol_spec::{
64    self, CatEntry, CompModeName, Face, MeritName, Radial, TolItem, TolSpec, VarSpec,
65};
66use lensbench_project::lenient;
67
68use lensbench_project::{Block, LensSource, Project};
69
70/// カタログの玉の既定の公差(メーカーによらない目安): 中心厚 ±0.1 mm・焦点距離 ±2%・芯取り 5′。偏心・傾き・間隔は
71/// 組立の公差なので、既定の組(`preset`)の値を使う。メーカーごとの公表値は `catalog_tols` で与える
72/// ([`catalog_rule`])
73pub fn catalog_lens_tol(base: LensTol) -> LensTol {
74    LensTol {
75        radius_rel: 0.0,
76        focal_rel: 0.02,
77        thickness: 0.1,
78        wedge: 5.0 / 60.0,
79        ..base
80    }
81}
82
83/// `catalog_tols` の 1 つのメーカーの値を、形 g(外径・焦点距離 [mm]・ガラスの枚数)の玉に当てる。値は玉の公差の項目
84/// ([`LensTol`] の名前)に、`rules`(外径・焦点距離の条件つきの上書きの並び。前から順に、条件が合うものを当てる):
85///
86/// ```json
87/// {"thickness": 0.1, "focal_rel": 0.01, "wedge": 0.05,
88///  "rules": [{"dia_lt": 10, "focal_rel": 0.02}, {"dia_le": 12, "thickness": 0.05}, {"efl_gt": 10, "wedge": 0.0167}]}
89/// ```
90///
91/// 条件は `dia_lt` `dia_le` `dia_gt` `dia_ge` `efl_lt` `efl_le` `efl_gt` `efl_ge`(焦点距離は絶対値で比べる)と
92/// `cemented`(true は貼り合わせ = ガラスが 2 枚以上の玉、false は単レンズ)。
93/// 1 つの規則に条件が複数あればすべてを満たすとき。外径・焦点距離が分からない(NaN)と条件は満たさない
94pub fn catalog_rule(
95    v: &Value,
96    base: LensTol,
97    g: LensGeom,
98    what: &str,
99) -> lensbench_core::Result<Option<LensTol>> {
100    let e: Option<CatEntry> = lenient::from_json(v, what)?;
101    cat_entry(e.as_ref(), base, g, what)
102}
103
104/// [`catalog_rule`] の型にした値
105fn cat_entry(
106    e: Option<&CatEntry>,
107    base: LensTol,
108    g: LensGeom,
109    what: &str,
110) -> lensbench_core::Result<Option<LensTol>> {
111    Ok(match e {
112        None => None,
113        Some(CatEntry::Preset(p)) => Some(tol_spec::preset(p, base).map_err(|e| e.at(what))?),
114        Some(CatEntry::Fields(f)) => {
115            let mut t = f.apply(base);
116            for r in f.rules.iter().flatten() {
117                if r.matches(g.dia, g.efl, g.glasses) {
118                    t = r.fields().apply(t);
119                }
120            }
121            Some(t)
122        }
123    })
124}
125
126/// 玉の形([`catalog_rule`] の条件)
127#[derive(Debug, Clone, Copy, PartialEq)]
128pub struct LensGeom {
129    /// 外径 [mm](面の半径の最大の 2 倍)
130    pub dia: f64,
131    /// 主波長の焦点距離 [mm]
132    pub efl: f64,
133    /// ガラスの枚数(貼り合わせなら 2 以上)
134    pub glasses: usize,
135}
136
137impl LensGeom {
138    pub const UNKNOWN: LensGeom = LensGeom {
139        dia: f64::NAN,
140        efl: f64::NAN,
141        glasses: 1,
142    };
143}
144
145/// 玉の名前(lens1 … と、同じ範囲のブロックの id)→ 玉の形
146fn lens_geometry(s: &System) -> HashMap<String, LensGeom> {
147    let mut m = HashMap::new();
148    let Ok(els) = lensbench_core::elements::split(s) else {
149        return m;
150    };
151    let lenses: Vec<_> = els
152        .iter()
153        .filter(|e| e.kind == lensbench_core::elements::Kind::Lens)
154        .collect();
155    for (k, e) in lenses.iter().enumerate() {
156        let dia = 2.0 * e.surfaces.iter().map(|d| d.semi).fold(0.0, f64::max);
157        let glasses = e
158            .surfaces
159            .iter()
160            .take(e.surfaces.len().saturating_sub(1))
161            .filter(|d| d.mat.is_medium() && !d.mat.is_air())
162            .count()
163            .max(1);
164        let g = LensGeom {
165            dia,
166            efl: e.efl(s.primary),
167            glasses,
168        };
169        let auto = format!("lens{}", k + 1);
170        if let Some(u) = s.units.iter().find(|u| u.auto && u.name == auto) {
171            // 鏡で折り返して往復する玉は、最初の範囲がこの玉のブロック
172            for v in s
173                .units
174                .iter()
175                .filter(|v| !v.auto && (v.spans == u.spans || v.spans.first() == u.spans.first()))
176            {
177                m.insert(v.name.clone(), g);
178            }
179        }
180        m.insert(auto, g);
181    }
182    m
183}
184
185/// プロジェクトのレンズカタログの玉: ブロックの id → メーカー
186pub fn catalog_vendors(p: &Project) -> HashMap<String, String> {
187    fn walk(bs: &[Block], m: &mut HashMap<String, String>) {
188        for b in bs {
189            match b {
190                Block::Lens {
191                    id,
192                    source: LensSource::Catalog { vendor, .. },
193                    ..
194                } if !id.is_empty() => {
195                    m.insert(id.clone(), vendor.clone());
196                }
197                Block::Group { blocks, .. } => walk(blocks, m),
198                _ => {}
199            }
200        }
201    }
202    let mut m = HashMap::new();
203    walk(&p.blocks, &mut m);
204    m
205}
206
207/// 裏返して置いた玉のブロックの id(`reversed` の玉。[`spec_from_json_with`] の reversed に渡す)
208pub fn reversed_lenses(p: &Project) -> HashSet<String> {
209    fn walk(bs: &[Block], m: &mut HashSet<String>) {
210        for b in bs {
211            match b {
212                Block::Lens {
213                    id, reversed: true, ..
214                } if !id.is_empty() => {
215                    m.insert(id.clone());
216                }
217                Block::Group { blocks, .. } => walk(blocks, m),
218                _ => {}
219            }
220        }
221    }
222    let mut m = HashSet::new();
223    walk(&p.blocks, &mut m);
224    m
225}
226
227/// "9.t"・"G1.shift=-1:1"・{"param", "lo", "hi", "configs"}
228fn var_from(v: &VarSpec, s: &System) -> lensbench_core::Result<Var> {
229    let (spec, lo, hi, configs) = match v {
230        VarSpec::Text(t) => match t.split_once('=') {
231            Some((a, r)) => {
232                let (l, h) = r
233                    .split_once(':')
234                    .ok_or_else(|| format!("the range of compensator {t} is min:max"))?;
235                let n = |x: &str, d: f64| -> lensbench_core::Result<f64> {
236                    if x.trim().is_empty() {
237                        Ok(d)
238                    } else {
239                        x.trim()
240                            .parse()
241                            .map_err(|_| format!("range {x} of compensator {t}").into())
242                    }
243                };
244                let (l, h) = (n(l, f64::NEG_INFINITY)?, n(h, f64::INFINITY)?);
245                (a.trim().to_string(), l, h, None)
246            }
247            None => (t.trim().to_string(), f64::NEG_INFINITY, f64::INFINITY, None),
248        },
249        VarSpec::Obj(o) => {
250            if o.configs.iter().flatten().any(|&k| k == 0) {
251                return Err(format!(
252                    "compensator {}: configs must be a list of configuration numbers (from 1)",
253                    o.param
254                )
255                .into());
256            }
257            (
258                o.param.clone(),
259                o.lo.unwrap_or(f64::NEG_INFINITY),
260                o.hi.unwrap_or(f64::INFINITY),
261                o.configs
262                    .as_ref()
263                    .map(|c| c.iter().map(|k| k - 1).collect()),
264            )
265        }
266    };
267    let p = s.param(&spec)?;
268    let v = Var::new(p).bounds(lo, hi);
269    Ok(match configs {
270        Some(c) => v.in_configs(c),
271        None => v,
272    })
273}
274
275fn tol_from(m: &TolItem, s: &System, dist: Dist, i: usize) -> lensbench_core::Result<Tol> {
276    let names: Vec<String> = match (&m.param, &m.params) {
277        (Some(p), None) => vec![p.clone()],
278        (None, Some(a)) => a.clone(),
279        _ => {
280            return Err(format!("tolerance {i}: either param (a string) or params (a list)").into())
281        }
282    };
283    // "j.nd"・"j.vd": モデルガラスの式で d 線の屈折率・アッベ数を変える(面の dnd・dvd に足す)
284    if let [n] = names.as_slice() {
285        if let Some((j, which)) = glass_dn_param(n) {
286            if m.scale.is_some() {
287                return Err(format!("tolerance {i}: {n} takes no scale").into());
288            }
289            if m.relative == Some(true) {
290                return Err(format!("tolerance {i}: {n} cannot be relative").into());
291            }
292            let g = glass_shift(s, j, which)
293                .map_err(|e| e.map_message(|e| format!("tolerance {i}: {e}")))?;
294            let mut t = tol_from(
295                &TolItem {
296                    param: Some(format!("{j}.dn")),
297                    params: None,
298                    scale: None,
299                    ..m.clone()
300                },
301                s,
302                dist,
303                i,
304            )?;
305            t.glass = Some(g);
306            t.label = m.label.clone().unwrap_or_else(|| n.clone());
307            return Ok(t);
308        }
309    }
310    let mut params = Vec::new();
311    for n in &names {
312        // "wave" はすべての波長(光源の波長のずれ。全波長を同じだけずらす)
313        if n.trim().eq_ignore_ascii_case("wave") {
314            params.extend((0..s.wavelengths.len()).map(|w| Param::new(0, Kind::Wave(w as u8))));
315            continue;
316        }
317        params.push(
318            s.param(n)
319                .map_err(|e| e.map_message(|e| format!("tolerance {i}: {e}")))?,
320        );
321    }
322    let (lo, hi) = match (m.pm, m.lo, m.hi) {
323        (Some(p), None, None) => (-p.abs(), p.abs()),
324        (None, Some(l), Some(h)) => (l, h),
325        _ => return Err(format!("tolerance {i}: pm or the pair lo and hi").into()),
326    };
327    let dist = m.dist.unwrap_or(dist);
328    let scale = m.scale.clone().unwrap_or_default();
329    if !scale.is_empty() && scale.len() != params.len() {
330        return Err(format!(
331            "tolerance {i}: scale must be a list of {} numbers, as many as the parameters ({} given)",
332            params.len(),
333            scale.len()
334        ).into());
335    }
336    Ok(Tol {
337        label: m.label.clone().unwrap_or_else(|| names.join("+")),
338        params,
339        lo,
340        hi,
341        relative: m.relative.unwrap_or(false),
342        dist,
343        scale,
344        glass: None,
345    })
346}
347
348/// "j.nd"・"j.vd"(面の番号 j と、nd なら false・vd なら true)
349fn glass_dn_param(n: &str) -> Option<(usize, bool)> {
350    let (j, k) = n.trim().split_once('.')?;
351    let j: usize = j.trim().parse().ok()?;
352    match k.trim() {
353        "nd" => Some((j, false)),
354        "vd" => Some((j, true)),
355        _ => None,
356    }
357}
358
359/// 面 j の媒質の d 線の屈折率(abbe が false)かアッベ数(true)のずれ([`GlassShift`])。
360/// 面の媒質がガラス(分散のある)かモデルガラスであることを確かめる
361pub fn glass_shift(s: &System, j: usize, abbe: bool) -> lensbench_core::Result<GlassShift> {
362    let d = s
363        .surfaces
364        .get(j)
365        .ok_or_else(|| format!("surface {j} does not exist"))?;
366    if d.grin().is_some() {
367        return Err(format!(
368            "surface {j}: nd and vd tolerances need a glass or a model glass, not a GRIN surface"
369        )
370        .into());
371    }
372    s.glass_nd_vd(&d.mat)
373        .map_err(|e| e.map_message(|e| format!("surface {j}: {e}")))?;
374    Ok(GlassShift { surf: j, abbe })
375}
376
377/// 設定の JSON を型に読む(null は空の設定)。誤りには欄の道が付く
378pub fn read_spec(v: &Value) -> lensbench_core::Result<TolSpec> {
379    if v.is_null() {
380        return Ok(TolSpec::default());
381    }
382    if !v.is_object() {
383        return Err("tolerance settings must be an object".into());
384    }
385    lenient::from_json(v, "tolerance")
386}
387
388/// 設定の JSON から [`McSpec`] を作る。vendors はブロックの id → メーカー([`catalog_vendors`]。.zmx なら空)。
389/// 裏返した玉は系の玉・群の印([`lensbench_core::units::Unit::flipped`]、プロジェクトの展開で付く)で分かる
390pub fn spec_from_json(
391    v: &Value,
392    configs: Vec<System>,
393    vendors: &HashMap<String, String>,
394) -> lensbench_core::Result<McSpec> {
395    spec_from_json_with(v, configs, vendors, &HashSet::new())
396}
397
398/// [`spec_from_json`] に、裏返して置いた玉の名前(ブロックの id、[`reversed_lenses`])を足したもの。`wedge_face` の
399/// 前・後ろは玉のもとの向き(カタログ・.zmx の向き)で決めるので、裏返した玉では系の中の面の順と逆になる。
400/// 名前は、系の玉・群に裏返しの印が無いとき(印を持たない系)だけ使う
401pub fn spec_from_json_with(
402    v: &Value,
403    configs: Vec<System>,
404    vendors: &HashMap<String, String>,
405    reversed: &HashSet<String>,
406) -> lensbench_core::Result<McSpec> {
407    let m = read_spec(v)?;
408    let s0 = configs.first().ok_or("no configurations")?.clone();
409    let dist = m.dist.unwrap_or(Dist::Normal { cut: 2.0 });
410    let mut base = LensTol::preset(m.preset.as_deref().unwrap_or("commercial"))?;
411    // ここでの wedge_first は玉のもとの向きで前の面か。系の面の順へは lens_fn で直す
412    if let Some(w) = m.wedge_face {
413        base.wedge_first = w == Face::Front;
414    }
415    let use_catalog = m.catalog.unwrap_or(true);
416    // メーカー名([`VendorKey::matches`]: 大文字小文字・空白・記号を無視して、ブロックのメーカー名に含まれれば合う。
417    // 複数が合えばいちばん長い(具体的な)名前。"*" はほかのすべて)→ 公差
418    let cat_over: Vec<(&String, VendorKey, &Option<CatEntry>)> = m
419        .catalog_tols
420        .iter()
421        .flatten()
422        .map(|(k, x)| (k, VendorKey::new(k), x))
423        .collect();
424    let find_cat = |vd: &str| -> Option<(&String, &Option<CatEntry>)> {
425        let u = VendorKey::new(vd);
426        cat_over
427            .iter()
428            .filter(|(k, key, _)| *k != "*" && !key.is_empty() && u.matches(key))
429            .max_by_key(|(_, key, _)| key.as_str().len())
430            .or_else(|| cat_over.iter().find(|(k, _, _)| *k == "*"))
431            .map(|(k, _, x)| (*k, *x))
432    };
433    let geom = lens_geometry(&s0);
434    let lens_base = |name: &str| -> lensbench_core::Result<LensTol> {
435        match vendors.get(name).filter(|_| use_catalog) {
436            Some(vd) => {
437                let g = geom.get(name).copied().unwrap_or(LensGeom::UNKNOWN);
438                let t = catalog_lens_tol(base);
439                match find_cat(vd) {
440                    Some((k, x)) => {
441                        let w = format!("catalog_tols.{k}");
442                        Ok(cat_entry(x.as_ref(), t, g, &w)?.unwrap_or_default())
443                    }
444                    None => Ok(t),
445                }
446            }
447            None => Ok(base),
448        }
449    };
450    let mut lens_over: HashMap<String, Option<LensTol>> = HashMap::new();
451    for (k, x) in m.lenses.iter().flatten() {
452        let b = lens_base(k)?;
453        let t = x.as_ref().map(|x| x.apply(b)).transpose();
454        lens_over.insert(k.clone(), t.map_err(|e| e.at(format!("lenses.{k}")))?);
455    }
456    let group_over: HashMap<String, Option<GroupTol>> = m
457        .groups
458        .iter()
459        .flatten()
460        .map(|(k, x)| (k.clone(), *x))
461        .collect();
462    // 名前の誤りを見つける
463    for k in lens_over.keys().chain(group_over.keys()) {
464        if s0.find_unit(k).is_none() {
465            return Err(format!("no lens or group {k}").into());
466        }
467    }
468    let base_err = std::cell::RefCell::new(None);
469    let lens_fn = |name: &str| -> Option<LensTol> {
470        let t = match lens_over.get(name) {
471            Some(t) => *t,
472            None => match lens_base(name) {
473                Ok(t) => Some(t),
474                Err(e) => {
475                    base_err.borrow_mut().get_or_insert(e);
476                    None
477                }
478            },
479        };
480        // 裏返した玉は、もとの向きの後ろの面が系の中では最初の面。系の玉・群に裏返しの印(Unit::flipped)があれば
481        // simple が直すので、ここでは印の無い系に名前で渡されたときだけ直す
482        let marked = s0.units.iter().any(|v| v.name == name && v.flipped);
483        t.map(|t| LensTol {
484            wedge_first: t.wedge_first != (reversed.contains(name) && !marked),
485            ..t
486        })
487    };
488    let group_fn = |name: &str| group_over.get(name).copied().flatten();
489    let mut tols = tolerance::simple(&s0, &lens_fn, &group_fn, dist);
490    if let Some(e) = base_err.into_inner() {
491        return Err(e);
492    }
493    for (i, x) in m.tols.iter().flatten().enumerate() {
494        tols.push(tol_from(x, &s0, dist, i + 1)?);
495    }
496    let mut p = Problem::new(configs);
497    let comp_mode = match m.comp_mode.unwrap_or(CompModeName::Optimize) {
498        CompModeName::Optimize => CompMode::Optimize,
499        CompModeName::Paraxial => CompMode::Paraxial,
500        CompModeName::None => CompMode::None,
501    };
502    // 補償子は DLS で合わせるときだけ(ほかの補償のしかたでは使わない。OpticStudio も同じ)
503    if comp_mode == CompMode::Optimize {
504        for x in m.compensators.iter().flat_map(|c| c.list()) {
505            p.vars.push(var_from(x, &s0)?);
506        }
507    }
508    let rings = m.rings.unwrap_or(3);
509    // 名前は CLI・Python と同じ reference
510    let reference = match m.reference.unwrap_or_default() {
511        RefName::Centroid => RmsRef::Centroid,
512        RefName::Chief => RmsRef::Chief,
513    };
514    match m.merit.unwrap_or(MeritName::Wavefront) {
515        MeritName::Wavefront => p.add_default(DefaultMerit::Wavefront, rings, reference),
516        MeritName::Spot => p.add_default(DefaultMerit::Spot, rings, reference),
517        MeritName::None => {}
518    }
519    if let Some(t) = &m.terms {
520        let ts = crate::merit::terms_from_json(t, &p.configs)?;
521        p.terms.extend(ts);
522    }
523    match &m.radial {
524        None | Some(Radial::On(false)) => {}
525        Some(Radial::On(true)) => {
526            tolerance::pair_disc(&mut tols, None);
527        }
528        Some(Radial::Dist(r)) => {
529            let normal = match Dist::parse(r) {
530                Ok(Dist::Uniform) => None,
531                Ok(Dist::Normal { cut }) => Some(cut),
532                _ => {
533                    return Err(format!(
534                        "radial must be true, false, uniform, normal or normal:σ ({r})"
535                    )
536                    .into())
537                }
538            };
539            tolerance::pair_disc(&mut tols, normal);
540        }
541    }
542    let mut spec = McSpec::new(p, tols);
543    spec.trials = m.trials.unwrap_or(spec.trials);
544    spec.seed = m.seed.unwrap_or(spec.seed);
545    if let Some(x) = m.comp_iters {
546        spec.comp = DlsOpts {
547            max_iter: x,
548            ..spec.comp
549        };
550    }
551    spec.sensitivity = m.sensitivity.unwrap_or(spec.sensitivity);
552    spec.comp_mode = comp_mode;
553    if let Some(x) = &m.inverse {
554        let target = match (x.limit, x.increment) {
555            (Some(l), None) => InverseTarget::Limit(l),
556            (None, Some(d)) => InverseTarget::Increment(d),
557            _ => return Err("inverse: give either limit or increment".into()),
558        };
559        let mut inv = Inverse::new(target);
560        if let Some(r) = x.rtol {
561            inv.rtol = r;
562        }
563        for name in x.skip.iter().flatten() {
564            let k: Vec<usize> = (0..spec.tols.len())
565                .filter(|&k| spec.tols[k].label == *name)
566                .collect();
567            if k.is_empty() {
568                return Err(format!("inverse.skip: no tolerance named {name}").into());
569            }
570            inv.skip.extend(k);
571        }
572        spec.inverse = Some(inv);
573        spec.sensitivity = true;
574    }
575    Ok(spec)
576}
577
578/// 公差の評価を書く一括実行のファイル([`crate::montecarlo::run_to`])の頭。設定 v(試行の数・出力だけの指定
579/// trials・threads・percentiles・samples は除く。試行を足して続きから回せる)・系の hash・玉のメーカーと裏返しから作る
580pub fn runs_header(
581    v: &Value,
582    configs: &[System],
583    vendors: &HashMap<String, String>,
584    reversed: &HashSet<String>,
585) -> lensbench_core::Result<String> {
586    let mut settings = v.clone();
587    if let Some(m) = settings.as_object_mut() {
588        for k in ["trials", "threads", "percentiles", "samples"] {
589            m.remove(k);
590        }
591    }
592    let systems = configs
593        .iter()
594        .map(lensbench_project::sysfile::system_hash)
595        .collect::<lensbench_core::Result<Vec<_>>>()?;
596    let vendors: std::collections::BTreeMap<_, _> = vendors.iter().collect();
597    let mut reversed: Vec<_> = reversed.iter().collect();
598    reversed.sort();
599    Ok(json!({
600        "lensbench": lensbench_core::VERSION,
601        "kind": "tolerance",
602        "settings": settings,
603        "systems": systems,
604        "vendors": vendors,
605        "reversed": reversed,
606    })
607    .to_string())
608}
609
610/// 設定の JSON の百分位・samples・threads
611pub struct OutOpts {
612    pub percentiles: Vec<f64>,
613    pub samples: bool,
614    pub threads: Option<usize>,
615}
616
617pub fn out_opts(v: &Value) -> lensbench_core::Result<OutOpts> {
618    let m = read_spec(v)?;
619    Ok(OutOpts {
620        percentiles: m
621            .percentiles
622            .unwrap_or_else(|| vec![50.0, 80.0, 90.0, 95.0, 98.0]),
623        samples: m.samples.unwrap_or(false),
624        threads: m.threads,
625    })
626}
627
628fn sorted(mut v: Vec<f64>) -> Vec<f64> {
629    v.retain(|x| x.is_finite());
630    v.sort_by(|a, b| a.total_cmp(b));
631    v
632}
633
634/// 項の説明("wavefront f1" など)
635/// 項の種類の名前(評価関数の JSON の type と同じ)。型の名前(Debug)から作らない
636fn kind_name(k: &lensbench_optim::TermKind) -> &'static str {
637    use lensbench_optim::TermKind as K;
638    match k {
639        K::Spot { .. } => "spot",
640        K::Wavefront { .. } => "wavefront",
641        K::Mtf { .. } => "mtf",
642        K::Paraxial { .. } => "paraxial",
643        K::Cardinal { .. } => "cardinal",
644        K::FNum { .. } => "fnum",
645        K::Seidel { .. } => "seidel",
646        K::Distortion { .. } => "distortion",
647        K::Energy { .. } => "energy",
648        K::Strehl { .. } => "strehl",
649        K::Param { .. } => "param",
650        K::Spread { .. } => "spread",
651        K::Diff { .. } => "diff",
652        K::Illum { .. } => "illum",
653        K::Longitudinal { .. } => "longitudinal",
654        K::LateralColor { .. } => "lateral_color",
655        K::SurfEach {
656            q: lensbench_optim::SurfQ::Semi,
657            ..
658        } => "semi",
659        K::SurfEach { .. } => "surface",
660        K::Centroid { .. } => "centroid",
661        K::Ray { .. } => "ray",
662        K::RayPath { .. } => "ray",
663        K::ParaxRay { .. } => "ray",
664        K::Opd { .. } => "opd",
665        K::Zernike { .. } => "zernike",
666        K::Coupling { .. } => "coupling",
667        K::Thickness { .. } => "thickness",
668        K::Surface { .. } => "surface",
669        K::Volume { .. } => "volume",
670        K::Shape {
671            q: lensbench_optim::ShapeQ::Tsag { .. },
672            ..
673        } => "tsag",
674        K::Shape { .. } => "bfs",
675        K::Calc { .. } => "calc",
676        K::User(_) => "user",
677    }
678}
679
680fn term_label(p: &Problem, k: usize) -> String {
681    let t = &p.terms[k];
682    let name = kind_name(&t.kind);
683    if p.configs.len() > 1 {
684        format!("{name} #{} (config {})", k + 1, t.config + 1)
685    } else {
686        format!("{name} #{}", k + 1)
687    }
688}
689
690/// 補償子の傾きの x・y の組: 同じ玉・群・面の `.tx` と `.ty` で、効く構成も同じもの。(名前, x の位置, y の位置)。
691/// 名前は「M.tilt」(面なら「5.tilt」)
692pub fn tilt_pairs(vars: &[Var], names: &[String]) -> Vec<(String, usize, usize)> {
693    let mut out = Vec::new();
694    for (qx, nx) in names.iter().enumerate() {
695        let Some(base) = nx.strip_suffix(".tx") else {
696            continue;
697        };
698        let ny = format!("{base}.ty");
699        if let Some(qy) = names
700            .iter()
701            .enumerate()
702            .position(|(q, n)| *n == ny && vars[q].configs == vars[qx].configs)
703        {
704            out.push((format!("{base}.tilt"), qx, qy));
705        }
706    }
707    out
708}
709
710/// 試行ごとの補償子の CSV([`result_json`] の結果から)。列は 試行(1 から)・評価関数・補償子・傾きの大きさ [分]。
711/// 追跡できなかった試行は値を空にする
712pub fn compensators_csv(result: &Value) -> lensbench_core::Result<String> {
713    let comps = result["compensators"]
714        .as_array()
715        .cloned()
716        .unwrap_or_default();
717    let tilts = result["tilt_magnitudes"]
718        .as_array()
719        .cloned()
720        .unwrap_or_default();
721    let merits = result["merit_values"]
722        .as_array()
723        .ok_or("the result has no per-trial values (merit_values)")?;
724    let n = merits.len();
725    let cols: Vec<(String, &Vec<Value>)> = comps
726        .iter()
727        .map(|c| (c["name"].as_str().unwrap_or("").to_string(), &c["values"]))
728        .chain(tilts.iter().map(|t| {
729            (
730                format!("{} [arcmin]", t["name"].as_str().unwrap_or("")),
731                &t["values"],
732            )
733        }))
734        .map(|(h, v)| {
735            v.as_array()
736                .filter(|a| a.len() == n)
737                .map(|a| (h.clone(), a))
738                .ok_or_else(|| format!("no per-trial values of compensator {h}"))
739        })
740        .collect::<Result<_, _>>()?;
741    let esc = |s: &str| {
742        if s.contains([',', '"', '\n']) {
743            format!("\"{}\"", s.replace('"', "\"\""))
744        } else {
745            s.to_string()
746        }
747    };
748    let cell = |v: &Value| v.as_f64().map_or(String::new(), |x| format!("{x}"));
749    let mut out = String::from("trial,merit");
750    for (h, _) in &cols {
751        out.push(',');
752        out.push_str(&esc(h));
753    }
754    out.push('\n');
755    for i in 0..n {
756        out.push_str(&format!("{},{}", i + 1, cell(&merits[i])));
757        for (_, a) in &cols {
758            out.push(',');
759            out.push_str(&cell(&a[i]));
760        }
761        out.push('\n');
762    }
763    Ok(out)
764}
765
766/// 結果の JSON([`report`] を JSON に)
767pub fn result_json(spec: &McSpec, r: &McResult, o: &OutOpts) -> Value {
768    serde_json::to_value(report(spec, r, o)).unwrap_or_default()
769}
770
771fn stats_info(v: &[f64], pcts: &[f64]) -> StatsInfo {
772    let st = tolerance::stats(v, pcts);
773    StatsInfo {
774        n: st.n,
775        mean: fin(st.mean),
776        std: fin(st.std),
777        min: fin(st.min),
778        max: fin(st.max),
779        percentiles: st.percentiles.iter().map(|&(p, x)| (p, fin(x))).collect(),
780    }
781}
782
783/// 結果(CLI・serve・GUI で同じ型)
784pub fn report(spec: &McSpec, r: &McResult, o: &OutOpts) -> ToleranceReport {
785    let s0 = &spec.problem.configs[0];
786    let pc = &o.percentiles;
787    let merits = r.merits();
788    let nm = r.nominal.merit;
789    let tolerances = spec
790        .tols
791        .iter()
792        .map(|t| TolInfo {
793            label: t.label.clone(),
794            params: t.params.iter().map(|&p| s0.param_name(p)).collect(),
795            lo: t.lo,
796            hi: t.hi,
797            relative: t.relative,
798            dist: t.dist.name(),
799            scale: (!t.scale.is_empty()).then(|| t.scale.clone()),
800        })
801        .collect();
802    let mut sens: Vec<(f64, SensInfo)> = r
803        .sensitivity
804        .iter()
805        .map(|x| {
806            let t = &spec.tols[x.tol];
807            let d = |e: &Option<tolerance::Eval>| e.as_ref().map(|e| e.merit - nm);
808            let comp = |e: &Option<tolerance::Eval>| {
809                e.as_ref()
810                    .filter(|e| !e.comp.is_empty())
811                    .map(|e| e.comp.clone())
812            };
813            let w = x.worst(nm);
814            // 逆感度で締めた範囲(感度の評価はその端のもの)
815            let (lo, hi) = r
816                .inverse
817                .as_ref()
818                .and_then(|v| v.get(x.tol))
819                .map_or((t.lo, t.hi), |v| (v.lo, v.hi));
820            (
821                w,
822                SensInfo {
823                    label: t.label.clone(),
824                    lo,
825                    hi,
826                    comp_lo: comp(&x.lo),
827                    comp_hi: comp(&x.hi),
828                    merit_lo: x.lo.as_ref().map(|e| e.merit),
829                    merit_hi: x.hi.as_ref().map(|e| e.merit),
830                    change_lo: d(&x.lo),
831                    change_hi: d(&x.hi),
832                    worst: fin(w),
833                },
834            )
835        })
836        .collect();
837    sens.sort_by(|a, b| b.0.total_cmp(&a.0));
838    // 感度の RSS による見積り(公称 + √Σ 変化²。変化² は lo 側と hi 側の平均で、OpticStudio と同じ)
839    let rss_estimate = (!r.sensitivity.is_empty()).then(|| {
840        let s2: f64 = sens
841            .iter()
842            .map(|(w, x)| {
843                let v: Vec<f64> = [x.change_lo, x.change_hi].into_iter().flatten().collect();
844                if !w.is_finite() || v.is_empty() {
845                    w * w
846                } else {
847                    v.iter().map(|c| c * c).sum::<f64>() / v.len() as f64
848                }
849            })
850            .sum();
851        nm + s2.sqrt()
852    });
853    let corr = r.correlation(&spec.tols);
854    let mut cv: Vec<(f64, CorrInfo)> = corr
855        .iter()
856        .zip(&spec.tols)
857        .map(|(&(r, ra), t)| {
858            let k = [r.abs(), ra.abs()]
859                .into_iter()
860                .filter(|x| x.is_finite())
861                .fold(f64::NEG_INFINITY, f64::max);
862            (
863                k,
864                CorrInfo {
865                    label: t.label.clone(),
866                    r: fin(r),
867                    r_abs: fin(ra),
868                },
869            )
870        })
871        .collect();
872    cv.sort_by(|a, b| b.0.total_cmp(&a.0));
873    let terms = (0..spec.problem.terms.len())
874        .map(|k| {
875            let v = r.term(k);
876            TermStats {
877                label: term_label(&spec.problem, k),
878                nominal: r.nominal.terms.get(k).copied(),
879                stats: stats_info(&v, pc),
880                cdf: sorted(v),
881            }
882        })
883        .collect();
884    // 補償子の試行ごとの値(試行の順、追跡できなかった試行は None)
885    let per_trial = |q: usize| -> Vec<Option<f64>> {
886        r.trials
887            .iter()
888            .map(|t| t.eval.as_ref().map(|e| e.comp[q]))
889            .collect()
890    };
891    let opt =
892        |v: &[Option<f64>]| -> Vec<Option<f64>> { v.iter().map(|x| x.and_then(fin)).collect() };
893    let names: Vec<String> = spec
894        .problem
895        .vars
896        .iter()
897        .map(|v| s0.param_name(v.param))
898        .collect();
899    let compensators = spec
900        .problem
901        .vars
902        .iter()
903        .enumerate()
904        .map(|(q, v)| {
905            let vals = per_trial(q);
906            let x: Vec<f64> = vals.iter().flatten().copied().collect();
907            CompStats {
908                name: names[q].clone(),
909                configs: v
910                    .configs
911                    .as_ref()
912                    .map(|c| c.iter().map(|k| k + 1).collect()),
913                nominal: r.nominal.comp.get(q).copied(),
914                stats: stats_info(&x, pc),
915                values: opt(&vals),
916            }
917        })
918        .collect();
919    // 傾きの x・y の組(同じ玉・群・面の tx と ty、効く構成も同じ)は大きさ √(tx² + ty²) を分で
920    let tilt_magnitudes = tilt_pairs(&spec.problem.vars, &names)
921        .into_iter()
922        .map(|(name, qx, qy)| {
923            let (vx, vy) = (per_trial(qx), per_trial(qy));
924            let vals: Vec<Option<f64>> = vx
925                .iter()
926                .zip(&vy)
927                .map(|(a, b)| Some(60.0 * a.as_ref()?.hypot(*b.as_ref()?)))
928                .collect();
929            let x: Vec<f64> = vals.iter().flatten().copied().collect();
930            let nominal = match (r.nominal.comp.get(qx), r.nominal.comp.get(qy)) {
931                (Some(a), Some(b)) => Some(60.0 * a.hypot(*b)),
932                _ => None,
933            };
934            TiltStats {
935                name,
936                x: names[qx].clone(),
937                y: names[qy].clone(),
938                unit: "arcmin".into(),
939                nominal,
940                stats: stats_info(&x, pc),
941                values: opt(&vals),
942            }
943        })
944        .collect();
945    let failed: Vec<&tolerance::Trial> = r.trials.iter().filter(|t| t.eval.is_none()).collect();
946    let mut errors: Vec<String> = Vec::new();
947    for t in &failed {
948        if let Some(e) = &t.error {
949            if !errors.contains(e) && errors.len() < 5 {
950                errors.push(e.clone());
951            }
952        }
953    }
954    let merit_values = opt(&r
955        .trials
956        .iter()
957        .map(|t| t.eval.as_ref().map(|e| e.merit))
958        .collect::<Vec<_>>());
959    ToleranceReport {
960        nominal: Some(r.nominal.clone()),
961        trials: r.trials.len(),
962        failed: failed.len(),
963        errors,
964        cancelled: r.cancelled,
965        seed: spec.seed,
966        tolerances,
967        merit: stats_info(&merits, pc),
968        cdf: sorted(merits),
969        terms,
970        compensators,
971        tilt_magnitudes,
972        merit_values,
973        sensitivity: sens.into_iter().map(|x| x.1).collect(),
974        rss_estimate,
975        correlation: cv.into_iter().map(|x| x.1).collect(),
976        comp_mode: match spec.comp_mode {
977            tolerance::CompMode::Optimize => "optimize",
978            tolerance::CompMode::Paraxial => "paraxial",
979            tolerance::CompMode::None => "none",
980        }
981        .into(),
982        inverse: match (&spec.inverse, &r.inverse) {
983            (Some(inv), Some(v)) => Some(InverseInfo {
984                mode: match inv.target {
985                    InverseTarget::Limit(_) => "limit",
986                    InverseTarget::Increment(_) => "increment",
987                }
988                .into(),
989                value: match inv.target {
990                    InverseTarget::Limit(x) | InverseTarget::Increment(x) => x,
991                },
992                limit: inv.limit(nm),
993                tightened: v.iter().filter(|x| x.tightened.iter().any(|b| *b)).count(),
994                tolerances: v
995                    .iter()
996                    .map(|x| InverseTolInfo {
997                        label: spec.tols[x.tol].label.clone(),
998                        lo0: x.lo0,
999                        hi0: x.hi0,
1000                        lo: x.lo,
1001                        hi: x.hi,
1002                        tightened_lo: x.tightened[0],
1003                        tightened_hi: x.tightened[1],
1004                        skipped: inv.skip.contains(&x.tol),
1005                    })
1006                    .collect(),
1007            }),
1008            _ => None,
1009        },
1010        samples: o.samples.then(|| {
1011            r.trials
1012                .iter()
1013                .map(|t| Sample {
1014                    deltas: t.deltas.clone(),
1015                    eval: t.eval.clone(),
1016                    error: t.error.clone(),
1017                })
1018                .collect()
1019        }),
1020        notes: None,
1021    }
1022}