Skip to main content

lensbench_design/
montecarlo.rs

1//! モンテカルロ公差シミュレーション。
2//!
3//! 公差([`Tol`])は系のパラメータ([`lensbench_core::param`] の [`Param`]: 厚さ・曲率半径・面の傾き偏心・屈折率のずれ・
4//! 玉や群の偏心・傾き・移動など)のずれの範囲 [lo, hi] と分布。1 つの公差が複数のパラメータを同じ乱数で
5//! 動かしてもよい(例: 玉の焦点距離 ±1% を、玉のすべての曲率半径を同じ比で変えて表す)。`relative` なら
6//! ずれは今の値に対する比(r → r (1 + δ))。
7//!
8//! 試行ごとに、すべての公差のずれを引いて系を作り、補償子([`lensbench_optim::Var`]: ピント・群の位置など)を
9//! 評価関数([`Problem`] の項)で DLS により合わせ直して([`McSpec::comp`])、評価関数と項の値を記録する。
10//! 評価量は最適化と同じ項(RMS 波面・RMS スポット・MTF・近軸量・利用者の項 など)で表す。
11//! 項の値([`Problem::term_values`])は、目標のある項(MTF など)ではその量そのもの、スポット・波面では RMS。
12//!
13//! 分布([`Dist`]):
14//! - `Uniform`: [lo, hi] の一様分布
15//! - `Normal`: 中心 (lo + hi)/2、標準偏差 (hi − lo)/(2 cut) の正規分布を [lo, hi] で切ったもの(既定 cut = 2、
16//!   範囲の端が ±2σ)
17//! - `End`: lo か hi を半々(最悪側の組合せを見る)
18//!
19//! 抽選: 公差の分布は一括実行の枠組みの抽選([`lensbench_runs::Draws`]、パラメータの掃引の [`lensbench_runs::Sampler`] と同じ
20//! 乱数・分布・円の中の組)で引く([`McSpec::draws`])。試行 i のずれは種と i だけで決まり、並列に回しても、スレッド数に
21//! よらず結果は同じになる。感度と試行の評価も一括実行の枠組み([`lensbench_runs::run`])で回す。
22//! 複数の構成(多重構成・ズームの各状態)は、同じずれをすべての構成に与える(同じ部品なので)。構成の間で
23//! 面の番号が同じであること(玉・群のパラメータは名前で付けた番号なので、玉・群の並びが同じであること)。
24//!
25//! 感度([`McSpec::sensitivity`]): 公差ごとに、その公差だけを lo・hi にした系を(補償して)評価し、
26//! 公称との差を出す(OpticStudio の感度解析の「最悪の項目」に当たる)。モンテカルロの結果からは、
27//! 評価関数とずれ δ・|δ| の相関([`McResult::correlation`])も出す。
28//!
29//! 補償のしかた([`CompMode`]、OpticStudio の公差解析の Comp): `Optimize` は補償子を評価関数で DLS により合わせ直す
30//! (Optimize All (DLS))。`Paraxial` は補償子を使わず、像面の前の厚さを置き直して公称の近軸の焦点からのずれを保つ
31//! (Paraxial Focus。像面の前の厚さの公差も打ち消す)。`None` は補償しない。
32//!
33//! 逆感度([`McSpec::inverse`]、OpticStudio の Inverse Limit・Inverse Increment): 感度の lo・hi で評価関数が上限
34//! (Limit: 評価関数の値、Increment: 公称からの変化)を超える側だけ、その公差の範囲を上限ちょうどになるまで締める
35//! (広げない。lo・hi は別々に解く)。試行(モンテカルロ)・感度の表・RSS の見積りは締めた範囲で求める([`InverseTol`])。
36//!
37//! 簡易設定([`simple`]): 玉ごとの公差の組([`LensTol`]、既定の組 [`LensTol::preset`])から公差の並びを作る。
38
39use lensbench_core::error::Result;
40use lensbench_core::invalid;
41use lensbench_core::par;
42use lensbench_core::param::{Kind, Param};
43use lensbench_core::system::System;
44use lensbench_core::units::UnitKind;
45use lensbench_core::LockExt;
46use lensbench_optim::{DlsOpts, Problem};
47use lensbench_runs::{self as runs, Draws, Joint};
48use std::sync::Mutex;
49
50mod inverse;
51use inverse::run_inverse;
52pub use inverse::{GlassShift, Inverse, InverseTarget, InverseTol};
53
54/// 分布。設定の JSON では名前の文字列("uniform"・"normal"・"normal:σの数"・"end"・"disc_x"・"disc_y:normal" など)
55#[derive(Debug, Clone, Copy, PartialEq, serde::Deserialize, schemars::JsonSchema)]
56#[serde(try_from = "String")]
57pub enum Dist {
58    Uniform,
59    /// 範囲の半分が cut σ の正規分布を範囲で切ったもの
60    Normal {
61        cut: f64,
62    },
63    /// lo か hi を半々
64    End,
65    /// 隣り合う 2 つの公差(x・y の組。[`pair_disc`])を、中心 (lo+hi)/2・半径 (hi−lo)/2 の円(楕円)の中で引く
66    /// 組の x。次の公差は同じ `normal` の [`Dist::DiscY`]。偏心・傾きの大きさが公差以下になる(x・y 別々の一様分布は角で √2 倍まで)。
67    /// `normal` が None なら円の中で一様、Some(cut) なら半径が cut σ の等方の 2 次元正規分布を円で切ったもの
68    DiscX {
69        normal: Option<f64>,
70    },
71    /// [`Dist::DiscX`] の組の y
72    DiscY {
73        normal: Option<f64>,
74    },
75}
76
77impl TryFrom<String> for Dist {
78    type Error = String;
79    fn try_from(s: String) -> std::result::Result<Dist, String> {
80        Dist::parse(&s).map_err(|e| e.to_string())
81    }
82}
83
84impl Dist {
85    pub fn parse(s: &str) -> Result<Dist> {
86        let l = s.trim().to_ascii_lowercase();
87        Ok(match l.as_str() {
88            "uniform" | "u" => Dist::Uniform,
89            "normal" | "gauss" | "n" => Dist::Normal { cut: 2.0 },
90            "end" | "ends" | "e" => Dist::End,
91            "disc_x" => Dist::DiscX { normal: None },
92            "disc_y" => Dist::DiscY { normal: None },
93            _ => {
94                // disc_x:normal・disc_x:normal:3(y も)
95                for (pre, y) in [("disc_x:", false), ("disc_y:", true)] {
96                    if let Some(r) = l.strip_prefix(pre) {
97                        let normal = match Dist::parse(r) {
98                            Ok(Dist::Normal { cut }) => Some(cut),
99                            Ok(Dist::Uniform) => None,
100                            _ => invalid!(
101                                "distribution {s} (disc_x, disc_x:normal, disc_x:normal:<number of σ>, and the same for y)"
102                            ),
103                        };
104                        return Ok(if y {
105                            Dist::DiscY { normal }
106                        } else {
107                            Dist::DiscX { normal }
108                        });
109                    }
110                }
111                // normal:3 のように σ の数を付けられる
112                if let Some(c) = l
113                    .strip_prefix("normal:")
114                    .and_then(|v| v.parse::<f64>().ok())
115                {
116                    if c > 0.0 {
117                        return Ok(Dist::Normal { cut: c });
118                    }
119                }
120                invalid!("distribution {s} (uniform, normal, normal:<number of σ>, end, or a disc_x and disc_y pair)")
121            }
122        })
123    }
124    pub fn name(&self) -> String {
125        match self {
126            Dist::Uniform => "uniform".into(),
127            Dist::Normal { cut } if *cut == 2.0 => "normal".into(),
128            Dist::Normal { cut } => format!("normal:{cut}"),
129            Dist::End => "end".into(),
130            Dist::DiscX { normal } | Dist::DiscY { normal } => {
131                let xy = if matches!(self, Dist::DiscX { .. }) {
132                    "x"
133                } else {
134                    "y"
135                };
136                match normal {
137                    None => format!("disc_{xy}"),
138                    Some(cut) => format!("disc_{xy}:{}", Dist::Normal { cut: *cut }.name()),
139                }
140            }
141        }
142    }
143}
144
145/// 公差 1 つ
146#[derive(Debug, Clone, PartialEq)]
147pub struct Tol {
148    /// 表示の名前("lens1 dx" など)
149    pub label: String,
150    /// 同じずれを与えるパラメータ(1 つ以上)
151    pub params: Vec<Param>,
152    pub lo: f64,
153    pub hi: f64,
154    /// ずれを今の値に対する比で与える
155    pub relative: bool,
156    pub dist: Dist,
157    /// パラメータごとにずれに掛ける数(空はすべて 1)。鏡で折り返して往復する玉の厚さのように、往きと戻りで同じずれを
158    /// 逆の符号で与えるときに -1
159    pub scale: Vec<f64>,
160    /// ガラスの nd・vd のずれ(params は面の [dn] で、確かめと表示の面の番号だけに使う。ずれは面の dnd・dvd に足す。
161    /// scale・relative は使わない)
162    pub glass: Option<GlassShift>,
163}
164
165impl Tol {
166    /// ±pm の一様分布
167    pub fn pm(label: impl Into<String>, param: Param, pm: f64) -> Tol {
168        Tol {
169            label: label.into(),
170            params: vec![param],
171            lo: -pm,
172            hi: pm,
173            relative: false,
174            dist: Dist::Uniform,
175            scale: Vec::new(),
176            glass: None,
177        }
178    }
179
180    /// パラメータ k のずれに掛ける数
181    pub fn scale_of(&self, k: usize) -> f64 {
182        self.scale.get(k).copied().unwrap_or(1.0)
183    }
184}
185
186/// モンテカルロの設定
187#[derive(Debug, Clone)]
188pub struct McSpec {
189    /// 評価関数(構成と項)。変数([`Problem::vars`])は補償子
190    pub problem: Problem,
191    pub tols: Vec<Tol>,
192    /// 試行の数(0 なら感度だけ)
193    pub trials: usize,
194    pub seed: u64,
195    /// 補償子の DLS の設定(反復は少なめでよい)
196    pub comp: DlsOpts,
197    /// 公差ごとの感度も求める
198    pub sensitivity: bool,
199    /// 補償のしかた
200    pub comp_mode: CompMode,
201    /// 逆感度(None ならしない)。感度も求める
202    pub inverse: Option<Inverse>,
203}
204
205/// 補償のしかた(OpticStudio の公差解析の Comp)
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
207pub enum CompMode {
208    /// 補償子([`Problem::vars`])を評価関数で DLS により合わせ直す(Optimize All (DLS))
209    #[default]
210    Optimize,
211    /// 補償子は使わず、構成ごとに像面の前の面の厚さを、近軸マージナル光線の焦点の動きだけ動かす(公称の焦点のずれを保つ。
212    /// Paraxial Focus)
213    Paraxial,
214    /// 補償しない
215    None,
216}
217
218impl McSpec {
219    pub fn new(problem: Problem, tols: Vec<Tol>) -> McSpec {
220        McSpec {
221            problem,
222            tols,
223            trials: 100,
224            seed: 1,
225            comp: DlsOpts {
226                max_iter: 10,
227                ..Default::default()
228            },
229            sensitivity: true,
230            comp_mode: CompMode::Optimize,
231            inverse: None,
232        }
233    }
234
235    pub fn check(&self) -> Result<()> {
236        self.problem.check()?;
237        if let Some(inv) = &self.inverse {
238            match inv.target {
239                InverseTarget::Limit(x) if !x.is_finite() => {
240                    invalid!("inverse limit {x} is not finite")
241                }
242                InverseTarget::Increment(x) if !(x.is_finite() && x > 0.0) => {
243                    invalid!("inverse increment {x} must be positive")
244                }
245                _ => {}
246            }
247            if !(inv.rtol.is_finite() && inv.rtol > 0.0) {
248                invalid!("inverse rtol {} must be positive", inv.rtol);
249            }
250            if let Some(&k) = inv.skip.iter().find(|&&k| k >= self.tols.len()) {
251                invalid!("inverse skip: no tolerance {k}");
252            }
253        }
254        if self.comp_mode == CompMode::Paraxial {
255            for s in &self.problem.configs {
256                let m = s.image().checked_sub(1).filter(|&m| m >= 1);
257                if m.is_none_or(|m| s.check_param(Param::new(m, Kind::Thick)).is_err()) {
258                    invalid!(
259                        "paraxial focus compensation needs a thickness before the image surface"
260                    );
261                }
262            }
263        }
264        for (i, t) in self.tols.iter().enumerate() {
265            if t.params.is_empty() {
266                invalid!("tolerance {i} ({}): no parameter", t.label);
267            }
268            if !t.scale.is_empty() && t.scale.len() != t.params.len() {
269                invalid!(
270                    "tolerance {i} ({}): scale has {} values (the parameters are {})",
271                    t.label,
272                    t.scale.len(),
273                    t.params.len()
274                );
275            }
276            if !(t.lo.is_finite() && t.hi.is_finite() && t.lo <= t.hi) {
277                invalid!("tolerance {i} ({}): range [{}, {}]", t.label, t.lo, t.hi);
278            }
279            let prev = i.checked_sub(1).map(|j| self.tols[j].dist);
280            let next = self.tols.get(i + 1).map(|u| u.dist);
281            let bad = match t.dist {
282                Dist::DiscX { normal } => next != Some(Dist::DiscY { normal }),
283                Dist::DiscY { normal } => prev != Some(Dist::DiscX { normal }),
284                _ => false,
285            };
286            if bad {
287                invalid!(
288                    "tolerance {i} ({}): a distribution in a circle puts y (disc_y) of the same distribution right after x (disc_x)",
289                    t.label
290                );
291            }
292            if let Dist::Normal { cut }
293            | Dist::DiscX { normal: Some(cut) }
294            | Dist::DiscY { normal: Some(cut) } = t.dist
295            {
296                if !(cut > 0.0) {
297                    invalid!(
298                        "tolerance {i} ({}): number of σ of the normal distribution {cut}",
299                        t.label
300                    );
301                }
302            }
303            for p in &t.params {
304                if p.kind.is_object() {
305                    invalid!(
306                        "tolerance {i} ({}): moving the object point is not system data",
307                        t.label
308                    );
309                }
310                for s in &self.problem.configs {
311                    s.check_param(*p)?;
312                    if s.pickup_of(*p).is_some() {
313                        invalid!(
314                            "tolerance {i} ({}): {} is set by a pickup (give it to the source surface)",
315                            t.label,
316                            s.param_name(*p)
317                        );
318                    }
319                }
320            }
321        }
322        Ok(())
323    }
324}
325
326/// 評価の結果(公称・試行・感度で共通)。一括実行のファイル([`run_to`])にも書く(有限でない値は null)
327#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
328pub struct Eval {
329    /// 評価関数の値(補償の後。有限でなければ null)
330    #[serde(deserialize_with = "nan_null::one")]
331    pub merit: f64,
332    /// 項ごとの値([`Problem::term_values`])
333    #[serde(with = "nan_null")]
334    pub terms: Vec<f64>,
335    /// 補償子の値(補償の後、変数の順)
336    #[serde(with = "nan_null")]
337    pub comp: Vec<f64>,
338}
339
340/// 有限でない値を null で書き、null を NaN で読む(JSON に NaN は書けない)
341mod nan_null {
342    use serde::{Deserialize, Deserializer, Serialize, Serializer};
343
344    pub(super) fn serialize<S: Serializer>(v: &[f64], s: S) -> Result<S::Ok, S::Error> {
345        v.iter()
346            .map(|x| x.is_finite().then_some(*x))
347            .collect::<Vec<_>>()
348            .serialize(s)
349    }
350
351    /// 1 つの値(null は NaN)
352    pub(super) fn one<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
353        Ok(Option::<f64>::deserialize(d)?.unwrap_or(f64::NAN))
354    }
355
356    pub(super) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<f64>, D::Error> {
357        Ok(Vec::<Option<f64>>::deserialize(d)?
358            .into_iter()
359            .map(|x| x.unwrap_or(f64::NAN))
360            .collect())
361    }
362}
363
364/// 一括実行のファイルの 1 行の結果(評価 1 つ)
365#[derive(serde::Serialize, serde::Deserialize)]
366struct Row {
367    #[serde(with = "nan_null")]
368    deltas: Vec<f64>,
369    eval: Option<Eval>,
370    error: Option<String>,
371}
372
373/// 試行 1 回
374#[derive(Debug, Clone, PartialEq)]
375pub struct Trial {
376    /// 公差ごとのずれ(relative なら比)
377    pub deltas: Vec<f64>,
378    /// 評価(追跡できなかった試行は None で、理由は error)
379    pub eval: Option<Eval>,
380    pub error: Option<String>,
381}
382
383/// 公差 1 つの感度
384#[derive(Debug, Clone, PartialEq)]
385pub struct Sens {
386    pub tol: usize,
387    /// lo・hi にしたときの評価(追跡できなければ None)
388    pub lo: Option<Eval>,
389    pub hi: Option<Eval>,
390}
391
392impl Sens {
393    /// 公称からの評価関数の変化の大きい方(追跡できなければ ∞)
394    pub fn worst(&self, nominal: f64) -> f64 {
395        let d = |e: &Option<Eval>| {
396            e.as_ref()
397                .map_or(f64::INFINITY, |e| (e.merit - nominal).abs())
398        };
399        d(&self.lo).max(d(&self.hi))
400    }
401}
402
403/// 統計
404#[derive(Debug, Clone, PartialEq)]
405pub struct Stats {
406    pub n: usize,
407    pub mean: f64,
408    pub std: f64,
409    pub min: f64,
410    pub max: f64,
411    /// (百分位, 値)
412    pub percentiles: Vec<(f64, f64)>,
413}
414
415/// 値の統計(有限の値だけ)。百分位は線形補間
416pub fn stats(values: &[f64], pcts: &[f64]) -> Stats {
417    let mut v: Vec<f64> = values.iter().copied().filter(|x| x.is_finite()).collect();
418    v.sort_by(|a, b| a.total_cmp(b));
419    let n = v.len();
420    if n == 0 {
421        return Stats {
422            n,
423            mean: f64::NAN,
424            std: f64::NAN,
425            min: f64::NAN,
426            max: f64::NAN,
427            percentiles: pcts.iter().map(|&p| (p, f64::NAN)).collect(),
428        };
429    }
430    let mean = v.iter().sum::<f64>() / n as f64;
431    let var = if n > 1 {
432        v.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64
433    } else {
434        0.0
435    };
436    let pct = |p: f64| {
437        let q = (p / 100.0).clamp(0.0, 1.0) * (n - 1) as f64;
438        let i = q.floor() as usize;
439        let f = q - i as f64;
440        if i + 1 < n {
441            v[i] + f * (v[i + 1] - v[i])
442        } else {
443            v[n - 1]
444        }
445    };
446    Stats {
447        n,
448        mean,
449        std: var.sqrt(),
450        min: v[0],
451        max: v[n - 1],
452        percentiles: pcts.iter().map(|&p| (p, pct(p))).collect(),
453    }
454}
455
456/// モンテカルロの結果
457#[derive(Debug, Clone, PartialEq)]
458pub struct McResult {
459    /// 公称の系の評価(補償子も合わせた後。試行の評価と同じ条件)
460    pub nominal: Eval,
461    pub trials: Vec<Trial>,
462    /// 公差の順(感度を求めなければ空)
463    pub sensitivity: Vec<Sens>,
464    /// 止めた(progress が false を返した)なら true。trials は終わった分だけ(試行の番号の順)
465    pub cancelled: bool,
466    /// 逆感度で締めた範囲(逆感度をしたときだけ、公差の順)。sensitivity の lo・hi の評価は締めた範囲の端のもの
467    pub inverse: Option<Vec<InverseTol>>,
468}
469
470impl McResult {
471    /// 追跡できた試行の評価関数の値
472    pub fn merits(&self) -> Vec<f64> {
473        self.trials
474            .iter()
475            .filter_map(|t| t.eval.as_ref().map(|e| e.merit))
476            .collect()
477    }
478
479    /// 項 k の値(追跡できた試行)
480    pub fn term(&self, k: usize) -> Vec<f64> {
481        self.trials
482            .iter()
483            .filter_map(|t| t.eval.as_ref().and_then(|e| e.terms.get(k).copied()))
484            .collect()
485    }
486
487    /// 公差ごとの、評価関数とずれの相関係数(Pearson): (ずれ δ との相関, |δ − 範囲の中心| との相関)。
488    /// 1 次の効き(ピントのずれなど、符号で良くも悪くもなる)は前、2 次の効き(偏心など、どちらに動いても悪くなる)は
489    /// 後に出る。試行が 3 回未満か、ずれが変わらない公差は NaN
490    pub fn correlation(&self, tols: &[Tol]) -> Vec<(f64, f64)> {
491        let ok: Vec<&Trial> = self.trials.iter().filter(|t| t.eval.is_some()).collect();
492        let m: Vec<f64> = ok
493            .iter()
494            .map(|t| {
495                t.eval
496                    .as_ref()
497                    .expect("only trials with an evaluation")
498                    .merit
499            })
500            .collect();
501        tols.iter()
502            .enumerate()
503            .map(|(i, t)| {
504                let c = 0.5 * (t.lo + t.hi);
505                let d: Vec<f64> = ok.iter().map(|x| x.deltas[i]).collect();
506                let a: Vec<f64> = d.iter().map(|x| (x - c).abs()).collect();
507                (pearson(&d, &m), pearson(&a, &m))
508            })
509            .collect()
510    }
511}
512
513fn pearson(a: &[f64], b: &[f64]) -> f64 {
514    let n = a.len();
515    if n < 3 {
516        return f64::NAN;
517    }
518    let ma = a.iter().sum::<f64>() / n as f64;
519    let mb = b.iter().sum::<f64>() / n as f64;
520    let (mut sab, mut saa, mut sbb) = (0.0, 0.0, 0.0);
521    for i in 0..n {
522        let (x, y) = (a[i] - ma, b[i] - mb);
523        sab += x * y;
524        saa += x * x;
525        sbb += y * y;
526    }
527    if saa > 0.0 && sbb > 0.0 {
528        sab / (saa * sbb).sqrt()
529    } else {
530        f64::NAN
531    }
532}
533
534// ------------------------------------------------------------------------------------------ 抽選
535
536impl Tol {
537    /// 抽選の分布([`lensbench_runs::Dist`]。範囲 [lo, hi] の中心と半幅で表し直す)。円の中の分布は組の 1 成分
538    pub fn sample_dist(&self) -> runs::Dist {
539        let (c, h) = (0.5 * (self.lo + self.hi), 0.5 * (self.hi - self.lo));
540        match self.dist {
541            Dist::Uniform => runs::Dist::Uniform {
542                lo: self.lo,
543                hi: self.hi,
544            },
545            Dist::Normal { cut } => runs::Dist::TruncNormal {
546                mean: c,
547                sigma: h / cut,
548                cut,
549            },
550            Dist::End => runs::Dist::End {
551                lo: self.lo,
552                hi: self.hi,
553            },
554            Dist::DiscX { normal } | Dist::DiscY { normal } => runs::Dist::Disc {
555                center: c,
556                radius: h,
557                normal,
558            },
559        }
560    }
561}
562
563impl McSpec {
564    /// 試行のずれの抽選([`lensbench_runs::Draws`])。隣り合う [`Dist::DiscX`]・[`Dist::DiscY`] を組にする
565    pub fn draws(&self) -> Result<Draws> {
566        let mut joints = Vec::new();
567        let mut k = 0;
568        while k < self.tols.len() {
569            if let (Dist::DiscX { normal }, Some(u)) = (self.tols[k].dist, self.tols.get(k + 1)) {
570                if u.dist == (Dist::DiscY { normal }) {
571                    joints.push(Joint::Disc { x: k, y: k + 1 });
572                    k += 2;
573                    continue;
574                }
575            }
576            k += 1;
577        }
578        let dists = self.tols.iter().map(Tol::sample_dist).collect();
579        Draws::new(dists, None, joints, self.seed)
580    }
581}
582
583// ------------------------------------------------------------------------------------------ 実行
584
585/// ずれ deltas を与えた構成
586pub fn perturbed(spec: &McSpec, deltas: &[f64]) -> Result<Vec<System>> {
587    if deltas.len() != spec.tols.len() {
588        invalid!(
589            "{} offsets (the tolerances are {})",
590            deltas.len(),
591            spec.tols.len()
592        );
593    }
594    spec.problem
595        .configs
596        .iter()
597        .map(|s| {
598            // 同じパラメータに 2 つの公差があれば足し合わせる
599            let mut ch: Vec<(Param, f64)> = Vec::new();
600            // ガラスの nd・vd のずれ(面, nd, vd)
601            let mut gl: Vec<(usize, f64, f64)> = Vec::new();
602            for (t, &d) in spec.tols.iter().zip(deltas) {
603                if d == 0.0 {
604                    continue;
605                }
606                if let Some(g) = &t.glass {
607                    let (a, b) = if g.abbe { (0.0, d) } else { (d, 0.0) };
608                    match gl.iter_mut().find(|x| x.0 == g.surf) {
609                        Some(x) => (x.1, x.2) = (x.1 + a, x.2 + b),
610                        None => gl.push((g.surf, a, b)),
611                    }
612                    continue;
613                }
614                for (k, &p) in t.params.iter().enumerate() {
615                    let v0 = s.get_param(p)?;
616                    let dv = t.scale_of(k) * if t.relative { v0 * d } else { d };
617                    match ch.iter_mut().find(|x| x.0 == p) {
618                        Some(x) => x.1 += dv,
619                        None => ch.push((p, v0 + dv)),
620                    }
621                }
622            }
623            let mut s = s.clone();
624            if !gl.is_empty() {
625                s.edit(|rx| {
626                    for &(j, a, b) in &gl {
627                        let d = &mut rx.surfaces[j];
628                        d.dnd += a;
629                        d.dvd += b;
630                    }
631                    Ok(())
632                })?;
633            }
634            if ch.is_empty() {
635                Ok(s)
636            } else {
637                s.with_params_fast(&ch)
638            }
639        })
640        .collect()
641}
642
643/// ずれ deltas の系を補償して評価する
644pub fn evaluate(spec: &McSpec, deltas: &[f64]) -> Result<Eval> {
645    let mut configs = perturbed(spec, deltas)?;
646    match spec.comp_mode {
647        CompMode::Optimize => {
648            let p = spec.problem.with_configs(configs);
649            eval_problem(&p, &spec.comp, true)
650        }
651        CompMode::Paraxial => {
652            for (c, s0) in configs.iter_mut().zip(&spec.problem.configs) {
653                *c = paraxial_focus(c, s0)?;
654            }
655            eval_fixed(&spec.problem.with_configs(configs))
656        }
657        CompMode::None => eval_fixed(&spec.problem.with_configs(configs)),
658    }
659}
660
661/// 補償しない評価(補償子の値は今の値)
662fn eval_fixed(p: &Problem) -> Result<Eval> {
663    eval_problem(p, &DlsOpts::default(), false)
664}
665
666/// 像面の前の面 m から近軸マージナル光線の焦点までの距離(主波長、鏡の向きも込み)
667fn paraxial_focus_distance(s: &System) -> Result<f64> {
668    let m = s.image() - 1;
669    let (y, u) = &s.paraxial().marginal;
670    let mirrors = s.surfaces[1..=m]
671        .iter()
672        .filter(|d| !d.ignore && d.is_mirror())
673        .count();
674    let sgn = if mirrors % 2 == 1 { -1.0 } else { 1.0 };
675    let z = -y[m] / (sgn * u[m]);
676    if !z.is_finite() {
677        invalid!("paraxial focus compensation: the marginal ray is parallel to the axis after surface {m}");
678    }
679    Ok(z)
680}
681
682/// ずらした系 s の像面の前の厚さを、近軸の焦点からのずれ(厚さ − 焦点までの距離)が公称の系 s0 と同じになるように
683/// 置いた系(OpticStudio の Paraxial Focus)。像面の前の厚さそのものの公差も打ち消す(OpticStudio 2026 R1.01 で
684/// その行の変化が 0 になることを確かめた)
685fn paraxial_focus(s: &System, s0: &System) -> Result<System> {
686    let m = s.image() - 1;
687    let p = Param::new(m, Kind::Thick);
688    let defocus0 = s0.get_param(p)? - paraxial_focus_distance(s0)?;
689    let t = paraxial_focus_distance(s)? + defocus0;
690    if t == s.get_param(p)? {
691        return Ok(s.clone());
692    }
693    s.with_params_fast(&[(p, t)])
694}
695
696fn eval_problem(p: &Problem, o: &DlsOpts, compensate: bool) -> Result<Eval> {
697    let x = if compensate && !p.vars.is_empty() {
698        lensbench_optim::dls_inner(p, o)?.x
699    } else {
700        p.x0()?
701    };
702    let (merit, terms) = p.merit_and_terms(&x)?;
703    let terms = terms.into_iter().map(|t| t.value()).collect();
704    Ok(Eval {
705        merit,
706        terms,
707        comp: x,
708    })
709}
710
711/// 評価の結果(追跡できなければ理由)
712type Outcome = std::result::Result<Eval, String>;
713
714/// 評価 1 つの結果の置き場(評価しなかったものは None)
715type Slot = Mutex<Option<(Vec<f64>, Outcome)>>;
716
717/// 試行 i のずれ([`McSpec::draws`] の i 番目。種と i だけで決まる)
718pub fn draw_trial(spec: &McSpec, i: usize) -> Result<Vec<f64>> {
719    Ok(spec.draws()?.draw(i))
720}
721
722/// 隣り合う x・y の公差の組(同じ面・玉・群の dx と dy、tx と ty。パラメータの数が同じもの)を、円の中の
723/// 分布([`Dist::DiscX`]・[`Dist::DiscY`]、normal が None で一様・Some(cut) で 2 次元正規)にする。偏心・傾き・くさびの
724/// 大きさを公差以下にしたいときに。組にした数を返す
725pub fn pair_disc(tols: &mut [Tol], normal: Option<f64>) -> usize {
726    use lensbench_core::param::Kind as K;
727    use lensbench_core::units::UnitKind as U;
728    let partner = |a: K| -> Option<K> {
729        Some(match a {
730            K::Dx => K::Dy,
731            K::Tx => K::Ty,
732            K::Unit(U::Dx) => K::Unit(U::Dy),
733            K::Unit(U::Tx) => K::Unit(U::Ty),
734            _ => return None,
735        })
736    };
737    let is_pair = |a: &Tol, b: &Tol| {
738        !a.relative
739            && !b.relative
740            && a.params.len() == b.params.len()
741            && a.scale == b.scale
742            && a.params
743                .iter()
744                .zip(&b.params)
745                .all(|(p, q)| p.index() == q.index() && partner(p.kind) == Some(q.kind))
746    };
747    let mut n = 0;
748    let mut k = 0;
749    while k + 1 < tols.len() {
750        if is_pair(&tols[k], &tols[k + 1]) {
751            tols[k].dist = Dist::DiscX { normal };
752            tols[k + 1].dist = Dist::DiscY { normal };
753            n += 1;
754            k += 2;
755        } else {
756            k += 1;
757        }
758    }
759    n
760}
761
762/// モンテカルロを回す。試行は並列に回す([`lensbench_core::par::with_threads`] に従う)。
763/// 試行・感度の評価が 1 つ終わるごとに、文脈の受け手([`par::with_progress`])へ [`par::Event::Count`] を別のスレッドから知らせる。
764/// 文脈の中断の印([`par::with_cancel`])が倒れたら新しい評価を始めず、そこまでの結果を返す(`cancelled`)
765/// 感度と試行は一括実行の枠組み([`lensbench_runs::run`]、ファイルには書かない)で回す
766pub fn run(spec: &McSpec) -> Result<McResult> {
767    run_to(spec, &runs::RunOpts::default())
768}
769
770/// [`run`] と同じ。o.out があれば評価(感度の lo・hi、試行)を 1 つずつ一括実行の JSONL に書き、o.resume なら
771/// 同じ頭(o.header)のファイルの続きから回す(書いた評価は飛ばす)。タスク k は k < 2×公差の数(感度があるとき)が感度、
772/// ほかは試行 k − 感度の数で、試行のずれは種と番号だけで決まるので、頭に試行の数を入れなければ試行を足して続きから回せる。
773/// o.threads は使う(None なら外の指定)、o.stage は使わない
774pub fn run_to(spec: &McSpec, o: &runs::RunOpts) -> Result<McResult> {
775    spec.check()?;
776    if spec.inverse.is_some() {
777        return run_inverse(spec, o);
778    }
779    let draws = spec.draws()?;
780    let nominal = match spec.comp_mode {
781        CompMode::Optimize => eval_problem(&spec.problem, &spec.comp, true)?,
782        _ => eval_fixed(&spec.problem)?,
783    };
784    let nt = spec.tols.len();
785    let ns = if spec.sensitivity { 2 * nt } else { 0 };
786    let total = ns + spec.trials;
787    // タスク k: k < ns は感度(公差 k/2 の lo・hi)、ほかは試行 k − ns
788    let deltas_of = |k: usize| -> Vec<f64> {
789        if k < ns {
790            let (i, hi) = (k / 2, k % 2 == 1);
791            let mut d = vec![0.0; nt];
792            d[i] = if hi { spec.tols[i].hi } else { spec.tols[i].lo };
793            d
794        } else {
795            draws.draw(k - ns)
796        }
797    };
798    // 止めた後の評価は None のまま(結果に出さない。追跡できなかった評価とは別)。評価の途中で止めたもの
799    // (補償が途中)も出さない
800    let out: Vec<Slot> = (0..total).map(|_| Mutex::new(None)).collect();
801    let ro = runs::RunOpts {
802        threads: o.threads,
803        out: o.out,
804        header: o.header.clone(),
805        resume: o.resume,
806        stage: "",
807        keep_going: false,
808    };
809    runs::run(total, spec.seed, &ro, |k, _| {
810        let deltas = deltas_of(k);
811        let r = evaluate(spec, &deltas);
812        if par::cancelled() {
813            // 空の結果はファイルに書かない(続きから回すときに評価し直す)
814            return Ok(String::new());
815        }
816        let r = match r {
817            Ok(e) if e.merit.is_finite() => Ok(e),
818            Ok(_) => Err("the merit function is not finite".into()),
819            Err(e) => Err(e.to_string()),
820        };
821        let line = match (o.out, &r) {
822            (None, _) => "0".to_string(),
823            (Some(_), r) => serde_json::to_string(&Row {
824                deltas: deltas.clone(),
825                eval: r.as_ref().ok().cloned(),
826                error: r.as_ref().err().cloned(),
827            })
828            .map_err(|e| lensbench_core::Error::Invalid(e.to_string()))?,
829        };
830        *out[k].lock_ok() = Some((deltas, r));
831        Ok(line)
832    })?;
833    let mut out: Vec<Option<(Vec<f64>, Outcome)>> = out
834        .into_iter()
835        .map(|m| m.into_inner().unwrap_or_else(|e| e.into_inner()))
836        .collect();
837    if let Some(path) = o.out {
838        // 続きから回して飛ばした評価はファイルから
839        let (_, rows) = runs::read_results(path)?;
840        for (k, _, txt) in rows {
841            if k < total && out[k].is_none() {
842                let r: Row = serde_json::from_str(&txt)
843                    .map_err(|e| format!("{}: evaluation {k}: {e}", path.display()))?;
844                let res = match (r.eval, r.error) {
845                    (Some(e), _) => Ok(e),
846                    (None, e) => Err(e.unwrap_or_default()),
847                };
848                out[k] = Some((r.deltas, res));
849            }
850        }
851    }
852    let trials_out = out.split_off(ns);
853    // 止めて lo・hi のどちらかを評価しなかった公差は感度に出さない
854    let sensitivity: Vec<Sens> = (0..ns / 2)
855        .filter_map(|i| match (&out[2 * i], &out[2 * i + 1]) {
856            (Some(lo), Some(hi)) => Some(Sens {
857                tol: i,
858                lo: lo.1.as_ref().ok().cloned(),
859                hi: hi.1.as_ref().ok().cloned(),
860            }),
861            _ => None,
862        })
863        .collect();
864    let trials = trials_out
865        .into_iter()
866        .flatten()
867        .map(|(deltas, r)| {
868            let (eval, error) = match r {
869                Ok(e) => (Some(e), None),
870                Err(e) => (None, Some(e)),
871            };
872            Trial {
873                deltas,
874                eval,
875                error,
876            }
877        })
878        .collect();
879    Ok(McResult {
880        nominal,
881        trials,
882        sensitivity,
883        cancelled: par::cancelled(),
884        inverse: None,
885    })
886}
887
888/// 玉ごとの公差の組(各値は ±、0 なら作らない)
889#[derive(Debug, Clone, Copy, PartialEq, Default)]
890pub struct LensTol {
891    /// 曲率半径の比(面ごとに独立、0.002 = ±0.2%)
892    pub radius_rel: f64,
893    /// 焦点距離の比(玉の曲率半径をすべて同じ比で変える。カタログの公差)
894    pub focal_rel: f64,
895    /// 中心厚 [mm](玉の中のガラスの厚さごと)
896    pub thickness: f64,
897    /// 面の傾き(くさび、玉の後ろの面の x・y の傾き)[deg]
898    pub wedge: f64,
899    /// 屈折率のずれ(ガラスごと)
900    pub dn: f64,
901    /// 分散の相対変化(アッベ数の比に当たる、ガラスごと)
902    pub disp: f64,
903    /// 玉の偏心 x・y [mm]
904    pub decenter: f64,
905    /// 玉の傾き x・y [deg]
906    pub tilt: f64,
907    /// 玉の後の空気の間隔 [mm](次に玉がある場合)
908    pub space: f64,
909    /// くさびを玉の前の面に入れる(false は後ろの面)。前・後ろは玉のもとの向きで、裏返して置いた玉([`lensbench_core::units::Unit::flipped`])
910    /// では系の中で光の通る順の逆(往復する玉は往きの範囲の順)
911    pub wedge_first: bool,
912}
913
914impl LensTol {
915    /// 既定の組: commercial(一般)・precision(精密)・high(高精度)。一般的な加工・組立の目安の値
916    /// (中心厚 ±0.15/0.05/0.025 mm、曲率半径 ±0.2/0.1/0.05%、くさび・傾き 3′/1′/0.5′、
917    /// 屈折率 ±0.001/0.0005/0.0002、アッベ数 ±1/0.8/0.5%、偏心 ±0.1/0.05/0.02 mm、間隔 ±0.1/0.05/0.02 mm)
918    pub fn preset(name: &str) -> Result<LensTol> {
919        let am = 1.0 / 60.0; // 1 分 [deg]
920        Ok(match name.trim().to_ascii_lowercase().as_str() {
921            "commercial" | "一般" => LensTol {
922                radius_rel: 0.002,
923                focal_rel: 0.0,
924                thickness: 0.15,
925                wedge: 3.0 * am,
926                dn: 0.001,
927                disp: 0.01,
928                decenter: 0.1,
929                tilt: 3.0 * am,
930                space: 0.1,
931                wedge_first: false,
932            },
933            "precision" | "精密" => LensTol {
934                radius_rel: 0.001,
935                focal_rel: 0.0,
936                thickness: 0.05,
937                wedge: 1.0 * am,
938                dn: 0.0005,
939                disp: 0.008,
940                decenter: 0.05,
941                tilt: 1.0 * am,
942                space: 0.05,
943                wedge_first: false,
944            },
945            "high" | "高精度" => LensTol {
946                radius_rel: 0.0005,
947                focal_rel: 0.0,
948                thickness: 0.025,
949                wedge: 0.5 * am,
950                dn: 0.0002,
951                disp: 0.005,
952                decenter: 0.02,
953                tilt: 0.5 * am,
954                space: 0.02,
955                wedge_first: false,
956            },
957            "none" => LensTol::default(),
958            n => invalid!("tolerance set {n} (commercial, precision, high, none)"),
959        })
960    }
961}
962
963/// 群・ブロック(玉でない玉・群)の公差(±、0 なら作らない)。設定の JSON の `groups` の値もこの型で読む(書かない項目は 0)
964#[derive(Debug, Clone, Copy, PartialEq, Default, serde::Deserialize, schemars::JsonSchema)]
965#[serde(default, deny_unknown_fields)]
966pub struct GroupTol {
967    /// 偏心 [mm]
968    pub decenter: f64,
969    /// 傾き [deg]
970    pub tilt: f64,
971    /// 光軸方向のずれ [mm]
972    pub shift: f64,
973}
974
975/// 簡易設定で公差の並びを作る。
976///
977/// - 玉([`System::lens_units`] で作った lens1 …)ごとに lens(名前) の組。名前は、同じ範囲のブロック・群の玉・群が
978///   あればその名前(ブロックの id)、なければ lens1 …。None の玉は公差を作らない
979/// - 群・ブロックは group(名前) の組(None なら作らない)。玉 1 つのブロックでは、玉の組とは別に足す(組立の公差)
980///
981/// 分布はすべて dist。ピックアップで決まるパラメータ・変えられないパラメータは除く
982pub fn simple(
983    s: &System,
984    lens: &dyn Fn(&str) -> Option<LensTol>,
985    group: &dyn Fn(&str) -> Option<GroupTol>,
986    dist: Dist,
987) -> Vec<Tol> {
988    let ok = |p: Param| s.check_param(p).is_ok() && s.pickup_of(p).is_none();
989    let mut out: Vec<Tol> = Vec::new();
990    // params は (パラメータ, ずれに掛ける数)
991    let mut push = |label: String, params: Vec<(Param, f64)>, pm: f64, relative: bool| {
992        let params: Vec<(Param, f64)> = params.into_iter().filter(|&(p, _)| ok(p)).collect();
993        if pm > 0.0 && !params.is_empty() {
994            let scale: Vec<f64> = if params.iter().all(|x| x.1 == 1.0) {
995                Vec::new()
996            } else {
997                params.iter().map(|x| x.1).collect()
998            };
999            out.push(Tol {
1000                label,
1001                params: params.into_iter().map(|x| x.0).collect(),
1002                lo: -pm,
1003                hi: pm,
1004                relative,
1005                dist,
1006                scale,
1007                glass: None,
1008            });
1009        }
1010    };
1011    let one = |p: Param| vec![(p, 1.0)];
1012    let auto: Vec<usize> = (0..s.units.len()).filter(|&u| s.units[u].auto).collect();
1013    let starts: Vec<usize> = auto.iter().map(|&u| s.units[u].spans[0][0]).collect();
1014    let links = lens_links(s);
1015    for (k, &u) in auto.iter().enumerate() {
1016        let unit = &s.units[u];
1017        // 往復する玉の 2 つ目からの範囲は、最初の範囲の玉にまとめる
1018        if links.iter().any(|l| l.others.iter().any(|o| o.auto == u)) {
1019            continue;
1020        }
1021        let link = links.iter().find(|l| l.first == u);
1022        // 同じ範囲のブロックの名前(往復する玉は範囲を全部持つブロック)
1023        let (name, mu) = match link {
1024            Some(l) => (s.units[l.unit].name.clone(), l.unit),
1025            None => s
1026                .units
1027                .iter()
1028                .position(|v| !v.auto && v.spans == unit.spans)
1029                .map_or((unit.name.clone(), u), |i| (s.units[i].name.clone(), i)),
1030        };
1031        let Some(t) = lens(&name) else { continue };
1032        let [a, b] = unit.spans[0];
1033        let others: Vec<LinkSpan> = link.map(|l| l.others.clone()).unwrap_or_default();
1034        // 面 j(最初の範囲)と、往復のほかの範囲の同じ面
1035        let surf = |j: usize, kind: Kind| -> Vec<(Param, f64)> {
1036            let mut v = vec![(Param::new(j, kind), 1.0)];
1037            for o in &others {
1038                v.push((Param::new(o.surf(a, j), kind), 1.0));
1039            }
1040            v
1041        };
1042        // 面 j の後の媒質(厚さ・屈折率)と、ほかの範囲の同じ媒質。厚さは逆向きの範囲では符号が逆
1043        let medium = |j: usize, kind: Kind, thick: bool| -> Vec<(Param, f64)> {
1044            let mut v = vec![(Param::new(j, kind), 1.0)];
1045            for o in &others {
1046                let f = if thick && o.reversed { -1.0 } else { 1.0 };
1047                v.push((Param::new(o.medium(a, j), kind), f));
1048            }
1049            v
1050        };
1051        let curved: Vec<usize> = (a..=b)
1052            .filter(|&j| {
1053                let d = &s.surfaces[j];
1054                d.c != 0.0 && ok(Param::new(j, Kind::Radius))
1055            })
1056            .collect();
1057        for &j in &curved {
1058            push(
1059                format!("{name} R{}", j - a + 1),
1060                surf(j, Kind::Radius),
1061                t.radius_rel,
1062                true,
1063            );
1064        }
1065        push(
1066            format!("{name} focal length"),
1067            curved.iter().flat_map(|&j| surf(j, Kind::Radius)).collect(),
1068            t.focal_rel,
1069            true,
1070        );
1071        let media: Vec<usize> = s
1072            .unit_media(u)
1073            .into_iter()
1074            .filter(|&j| (a..=b).contains(&j))
1075            .collect();
1076        for &j in &media {
1077            if j < b {
1078                push(
1079                    format!("{name} thickness {}", j - a + 1),
1080                    medium(j, Kind::Thick, true),
1081                    t.thickness,
1082                    false,
1083                );
1084            }
1085        }
1086        for &j in &media {
1087            push(
1088                format!("{name} index {}", j - a + 1),
1089                medium(j, Kind::Dn, false),
1090                t.dn,
1091                false,
1092            );
1093            push(
1094                format!("{name} dispersion {}", j - a + 1),
1095                medium(j, Kind::Disp, false),
1096                t.disp,
1097                false,
1098            );
1099        }
1100        // くさびは最後(wedge_first なら最初)の面の傾き。往復の同じ面に同じ符号(往復の範囲を持つ玉の剛体の傾きと同じ向き)
1101        let flipped = s.units[u].flipped || s.units[mu].flipped;
1102        let wf = if t.wedge_first != flipped { a } else { b };
1103        push(
1104            format!("{name} wedge x"),
1105            surf(wf, Kind::Tx),
1106            t.wedge,
1107            false,
1108        );
1109        push(
1110            format!("{name} wedge y"),
1111            surf(wf, Kind::Ty),
1112            t.wedge,
1113            false,
1114        );
1115        push(
1116            format!("{name} decenter x"),
1117            one(Param::unit(mu, UnitKind::Dx)),
1118            t.decenter,
1119            false,
1120        );
1121        push(
1122            format!("{name} decenter y"),
1123            one(Param::unit(mu, UnitKind::Dy)),
1124            t.decenter,
1125            false,
1126        );
1127        push(
1128            format!("{name} tilt x"),
1129            one(Param::unit(mu, UnitKind::Tx)),
1130            t.tilt,
1131            false,
1132        );
1133        push(
1134            format!("{name} tilt y"),
1135            one(Param::unit(mu, UnitKind::Ty)),
1136            t.tilt,
1137            false,
1138        );
1139        if k + 1 < starts.len() && b < starts[k + 1] {
1140            // 玉の後の間隔。逆向きの範囲では範囲の前の間隔(符号が逆)
1141            let mut v = vec![(Param::new(b, Kind::Thick), 1.0)];
1142            for o in &others {
1143                if let Some((j, f)) = o.space() {
1144                    v.push((Param::new(j, Kind::Thick), f));
1145                }
1146            }
1147            push(format!("{name} space after"), v, t.space, false);
1148        }
1149    }
1150    for u in 0..s.units.len() {
1151        let unit = &s.units[u];
1152        if unit.auto {
1153            continue;
1154        }
1155        let Some(g) = group(&unit.name) else { continue };
1156        // 玉 1 つのブロック(往復する玉も)は玉の公差の偏心・傾きと別に足す(組立の公差)。名前は「group」を付けて分ける
1157        let is_lens = s.units.iter().any(|v| v.auto && v.spans == unit.spans)
1158            || links.iter().any(|l| l.unit == u);
1159        let name = &unit.name;
1160        let lab = |g: String, b: String| if is_lens { g } else { b };
1161        push(
1162            lab(
1163                format!("{name} group decenter x"),
1164                format!("{name} decenter x"),
1165            ),
1166            one(Param::unit(u, UnitKind::Dx)),
1167            g.decenter,
1168            false,
1169        );
1170        push(
1171            lab(
1172                format!("{name} group decenter y"),
1173                format!("{name} decenter y"),
1174            ),
1175            one(Param::unit(u, UnitKind::Dy)),
1176            g.decenter,
1177            false,
1178        );
1179        push(
1180            lab(format!("{name} group tilt x"), format!("{name} tilt x")),
1181            one(Param::unit(u, UnitKind::Tx)),
1182            g.tilt,
1183            false,
1184        );
1185        push(
1186            lab(format!("{name} group tilt y"), format!("{name} tilt y")),
1187            one(Param::unit(u, UnitKind::Ty)),
1188            g.tilt,
1189            false,
1190        );
1191        push(
1192            lab(format!("{name} group shift"), format!("{name} shift")),
1193            one(Param::unit(u, UnitKind::Shift)),
1194            g.shift,
1195            false,
1196        );
1197    }
1198    out
1199}
1200
1201/// 往復する玉の 2 つ目からの範囲(自動の玉の番号と、最初の範囲に対する向き)
1202#[derive(Debug, Clone, Copy, PartialEq)]
1203struct LinkSpan {
1204    /// 自動の玉(lens1 …)の番号
1205    auto: usize,
1206    /// 範囲 [始め, 終わり]
1207    span: [usize; 2],
1208    /// 最初の範囲と逆向きにたどる(鏡で折り返した戻り)
1209    reversed: bool,
1210    /// 範囲の前の面(逆向きの範囲の前の間隔の面)
1211    before: Option<usize>,
1212}
1213
1214impl LinkSpan {
1215    /// 最初の範囲が a から始まるときの、最初の範囲の面 j と同じ面
1216    fn surf(&self, a: usize, j: usize) -> usize {
1217        let k = j - a;
1218        if self.reversed {
1219            self.span[1] - k
1220        } else {
1221            self.span[0] + k
1222        }
1223    }
1224    /// 最初の範囲の面 j の後の媒質と同じ媒質の面(その面の後の媒質)
1225    fn medium(&self, a: usize, j: usize) -> usize {
1226        let k = j - a;
1227        if self.reversed {
1228            self.span[1] - k - 1
1229        } else {
1230            self.span[0] + k
1231        }
1232    }
1233    /// 最初の範囲の後の間隔と同じ間隔の面と、ずれに掛ける数
1234    fn space(&self) -> Option<(usize, f64)> {
1235        if self.reversed {
1236            self.before.map(|j| (j, -1.0))
1237        } else {
1238            Some((self.span[1], 1.0))
1239        }
1240    }
1241}
1242
1243/// 鏡で折り返して同じ玉を往復する(範囲が 2 つ以上あり、どの範囲も自動の玉の範囲と同じ)ブロックの玉
1244#[derive(Debug, Clone)]
1245struct LensLink {
1246    /// 往復の範囲を持つ玉(ブロック)の番号
1247    unit: usize,
1248    /// 最初の範囲の自動の玉の番号
1249    first: usize,
1250    others: Vec<LinkSpan>,
1251}
1252
1253fn lens_links(s: &System) -> Vec<LensLink> {
1254    // 置き方(偏心・傾き)つきのブロックの範囲は前後の座標ブレークを含むので、玉の面だけの範囲にする
1255    let trim = |sp: &[usize; 2]| {
1256        let cb = |j: usize| s.surfaces[j].typ() == lensbench_core::surface::SurfType::CoordBrk;
1257        let [mut a, mut b] = *sp;
1258        while a < b && cb(a) {
1259            a += 1;
1260        }
1261        while b > a && cb(b) {
1262            b -= 1;
1263        }
1264        [a, b]
1265    };
1266    let auto_of = |sp: &[usize; 2]| {
1267        s.units
1268            .iter()
1269            .position(|v| v.auto && v.spans.len() == 1 && v.spans[0] == *sp)
1270    };
1271    let mut out = Vec::new();
1272    for (i, u) in s.units.iter().enumerate() {
1273        if u.auto || u.spans.len() < 2 {
1274            continue;
1275        }
1276        let spans: Vec<[usize; 2]> = u.spans.iter().map(trim).collect();
1277        let Some(autos) = spans.iter().map(auto_of).collect::<Option<Vec<usize>>>() else {
1278            continue;
1279        };
1280        let [a, b] = spans[0];
1281        let n = b - a;
1282        let dir = |sp: &[usize; 2]| s.surfaces[sp[0]].t.signum();
1283        let mut others = Vec::new();
1284        let mut fine = true;
1285        for (k, sp) in spans.iter().enumerate().skip(1) {
1286            if sp[1] - sp[0] != n {
1287                fine = false;
1288                break;
1289            }
1290            others.push(LinkSpan {
1291                auto: autos[k],
1292                span: *sp,
1293                reversed: dir(sp) != dir(&spans[0]),
1294                before: sp[0].checked_sub(1),
1295            });
1296        }
1297        if fine {
1298            out.push(LensLink {
1299                unit: i,
1300                first: autos[0],
1301                others,
1302            });
1303        }
1304    }
1305    out
1306}