Skip to main content

lensbench_core/
param.rs

1//! 系を作り直さずにパラメータを変える。
2//!
3//! 面は番号か名前(コメント)で選ぶ。変えたパラメータが影響しないキャッシュ(面の座標系・近軸量)は残す。
4//! 変えた後の系は、同じ値で .zmx から読み直した系と同じデータになり、追跡はビット一致する
5//! (屈折率のずれ dn・disp は .zmx に書けないので除く)。
6//!
7//! パラメータの意味:
8//! - `c`(曲率)・`r`(曲率半径、0 は平面)・`k`(円錐係数)・`a2`〜`a16`(偶数次非球面の r^2〜r^16 の係数)
9//! - `t`: 次の面までの厚さ(面 0 は物体距離)
10//! - `dx` `dy` `tx` `ty` `tz`: 座標ブレークならその値。ほかの面では面の前の傾き偏心(OpticStudio の
11//!   Tilt/Decenter の「前」)。前の傾き偏心がない面に与えると、面の後は「前を戻す」になる(その面だけが動く)。
12//!   既にある面では面の後の扱いを変えない
13//! - `dn`: 面の後の媒質の屈折率に全波長で足すずれ
14//! - `disp`: 同じ媒質の分散の相対変化。n = n0(λ) + dn + disp·(n0(λ) − n0(主波長))
15//!
16//! 媒質は鏡・座標ブレークを越えて続くので、dn・disp はその後に続く鏡・座標ブレークの面にも反映する。
17//! 物点の移動(`objx` `objy`)は系のデータではなく追跡の入力なので、ここでは変えない(微分 [`crate::fermat`] で使う)。
18//!
19//! ピックアップ([`crate::pickup::Pickup`]、.zmx の曲率・厚さ・円錐係数・パラメータのピックアップ)は OpticStudio と同じく追従する:
20//! 元の面のパラメータを変えると、ピックアップ先も「倍率 × 元の値 + オフセット」に解決し直す。
21//! ピックアップ先のパラメータそのものは変えられない(エラー。元の面を変える)。
22//! 玉の並びを組み直した系([`crate::elements::assemble`])はピックアップを引き継がない。
23//!
24//! 玉・群の単位のパラメータ([`crate::units`])も同じ形で指す: `lens2.tx`(玉モードの 2 番目の玉の傾き)、
25//! `G1.shift`(群 G1 の移動)。[`Param::surf`] は玉・群の番号([`System::units`])、種類は [`Kind::Unit`]。
26//! 名前が面の名前(コメント)と玉・群の名前の両方にあるときは、`unit:名前.種類` `surf:名前.種類` で区別する。
27
28use crate::error::Result;
29use crate::material::Material;
30use crate::pickup::pick_kind;
31use crate::pupil::Apodization;
32use crate::solves::solve_kind_info;
33use crate::surface::{After, Aperture, Tilt};
34use crate::system::{Aiming, ApertureKind, Keep, System};
35use crate::units::UnitKind;
36
37mod keep;
38mod kind_preds;
39mod solve;
40mod table;
41use crate::{invalid, notimpl};
42pub(crate) use keep::keep_for;
43pub use solve::{set_solve_value, solve_value};
44pub use table::set_surface_table_value;
45use table::{aperture_decenter, aperture_os_code};
46
47/// パラメータの種類
48#[derive(
49    Debug,
50    Clone,
51    Copy,
52    PartialEq,
53    Eq,
54    Hash,
55    serde::Serialize,
56    serde::Deserialize,
57    schemars::JsonSchema,
58)]
59pub enum Kind {
60    /// 曲率 c
61    Curv,
62    /// 曲率半径 R = 1/c(0 は平面)
63    Radius,
64    /// 円錐係数
65    Conic,
66    /// 偶数次非球面の係数(0 が r^2、7 が r^16)
67    Asph(u8),
68    /// Zernike Sag の面の項 j の係数(1 から)
69    Zern(u16),
70    /// 次の面までの厚さ
71    Thick,
72    Dx,
73    Dy,
74    /// 傾き [deg]
75    Tx,
76    Ty,
77    Tz,
78    /// 媒質の屈折率のずれ
79    Dn,
80    /// 媒質の分散の相対変化
81    Disp,
82    /// 物点の x・y(有限物体。面の番号は使わない)
83    ObjX,
84    ObjY,
85    /// 系の波長 i(0 始まり、名前は wave1 から)[µm]。面の番号は使わない。変えると全媒質の屈折率がその波長の値になる
86    /// (光源の波長のずれの公差・多重構成の行(.zmx の WAVE)用。最適化の変数には使えない)
87    Wave(u8),
88    /// 系の波長 i の重み(0 始まり、名前は wwt1 から)。多重構成の行(.zmx の WLWT)。最適化の変数には使えない
89    WaveW(u8),
90    /// 主波長の番号(1 から。値は整数)。多重構成の行(.zmx の PRWV)。最適化の変数には使えない
91    Primary,
92    /// 開口の値(開口の種類の単位: 入射瞳径 mm・F 値・NA など)。多重構成の行(.zmx の APER)。最適化の変数には使えない
93    Aper,
94    /// 開口の種類(OpticStudio の番号 0〜5: 入射瞳径・像側 F 値・物体側 NA・絞り径・近軸作動 F 値・物体側の開き角)。
95    /// 多重構成の行(.zmx の SATP)。最適化の変数には使えない
96    ApertureType,
97    /// 絞りの面の番号(値は整数)。多重構成の行(.zmx の STPS)。最適化の変数には使えない
98    Stop,
99    /// 視野の種類(OpticStudio の番号 0〜3: 角度・物体高・近軸像高・実像高)。多重構成の行(.zmx の FLTP)。
100    /// 最適化の変数には使えない
101    FieldType,
102    /// 系の温度 [°C]・気圧 [atm](変えると全媒質の屈折率を作り直す)。多重構成の行(.zmx の TEMP・PRES)。最適化の変数には使えない
103    Temp,
104    Pres,
105    /// アフォーカルの像空間か(1 でアフォーカル)。多重構成の行(.zmx の AFOC)。最適化の変数には使えない
106    Afocal,
107    /// アポダイゼーションの種類(OpticStudio の番号 0〜2: 一様・ガウス・cos³)と、ガウスの係数。多重構成の行
108    /// (.zmx の APDT・APDF)。最適化の変数には使えない
109    ApodType,
110    Apod,
111    /// 光線エイミング(0〜2: なし・近軸・実光線)。多重構成の行(.zmx の RAAM)。最適化の変数には使えない
112    Aiming,
113    /// OPD の基準(OpticStudio の番号 0〜3、.zmx の ROPD と同じ)。多重構成の行(.zmx の OPDR)。最適化の変数には使えない
114    Ropd,
115    /// 光線エイミングの瞳のずれ x・y・z(0〜2)と圧縮 x・y(3・4)。名前は pshx・pshy・pshz・pscx・pscy。多重構成の行
116    /// (.zmx の PSHX〜PSCY)。追跡には効かない([`crate::system::AimPupil`])。最適化の変数には使えない
117    AimPupil(u8),
118    /// 系の入射偏光の偏光なし(1 か 0)・振幅 x・y・位相 x・y [deg](0〜4)。名前は polun・poljx・poljy・polpx・polpy。
119    /// 多重構成の行(.zmx の GPIU・GPJX・GPJY・GPPX・GPPY)。[`crate::system::InputPolarization`]。最適化の変数には使えない
120    InputPol(u8),
121    /// 視野 i の x・y・重み(0 始まり、名前は fx1・fy1・fwt1 から)。多重構成の行(.zmx の XFIE・YFIE・FLWT)。
122    /// 最適化の変数には使えない
123    FieldX(u8),
124    FieldY(u8),
125    FieldW(u8),
126    /// 視野 i(0 始まり)のけられ係数 j(0〜4 = VDX・VDY・VCX・VCY・VAN、名前は vdx1・vdy1・vcx1・vcy1・van1 から)。
127    /// 多重構成の行(.zmx の FVDX・FVDY・FVCX・FVCY・FVAN・FTAN)。最適化の変数には使えない
128    FieldVig(u8, u8),
129    /// 玉・群のパラメータ(付く先は [`Target::Unit`])
130    Unit(UnitKind),
131    /// 半直径(semi-diameter)。ピックアップ・マクロのソルブの量と、多重構成の行(.zmx の SDIA。固定の半直径にし、
132    /// 浮動開口の面はその半直径でける)。最適化の変数には使えない
133    Semi,
134    /// 面を無視するか(1 で無視、0 で使う)。多重構成の行(.zmx の IGNR)。最適化の変数には使えない
135    Ignore,
136    /// 円形の開口・遮蔽の最大の半径。多重構成の行(.zmx の APMX)。最適化の変数には使えない
137    ApMax,
138    /// 円形の開口・遮蔽の最小の半径。多重構成の行(.zmx の APMN)。最適化の変数には使えない
139    ApMin,
140    /// 開口・遮蔽の偏心 x・y。多重構成の行(.zmx の APDX・APDY)。最適化の変数には使えない
141    ApDx,
142    ApDy,
143    /// 開口の種類(OpticStudio の番号: 0 なし・1 円形の開口・2 円形の遮蔽・3 スパイダー・4 矩形・6 楕円・10 浮動。
144    /// 変えられるのは 0〜2 の間で、半径は今の円形の開口・遮蔽の値)。多重構成の行(.zmx の APTP)。最適化の変数には使えない
145    ApType,
146    /// 面の前・後の傾き偏心の順序(0 偏心から、1 傾きから)。多重構成の行(.zmx の CBOR・CAOR)。最適化の変数には使えない
147    BeforeOrder,
148    AfterOrder,
149    /// モデルガラスの nd・vd・ΔPgF(面の材料がモデルガラスのときだけ)。多重構成の行(.zmx の MIND・MABB・MDPG)。
150    /// 最適化の変数には使えない
151    ModelNd,
152    ModelVd,
153    ModelDpgf,
154    /// 面の熱膨張係数 [1e-6/°C]([`crate::surface::Surface::tce`])。多重構成の行(.zmx の TCEX)。最適化の変数には使えない
155    Tce,
156    /// 面の機械半径([`System::lens_radius`]、設定すると固定)・チップゾーン([`crate::surface::Surface::chip_zone`])。
157    /// 多重構成の行(.zmx の MCSD・CHZN)。最適化の変数には使えない
158    MechSemi,
159    ChipZone,
160    /// 座標ブレークの座標の戻り([`crate::surface::Surface::coord_return`])の戻し方(OpticStudio の番号 0〜3)と戻り先の面。
161    /// 名前は cror・crsr。多重構成の行(.zmx の CROR・CRSR)。最適化の変数には使えない
162    CoordRet,
163    CoordRetSurf,
164    /// 面の曲率・厚さのソルブ(ピックアップを含む)の条件の値 i(0 始まり、名前は csp1・tsp1 から)と、面タイプのパラメータ
165    /// n のピックアップの値 i(名前は psp1_n から)。値の番号は OpticStudio のソルブの窓の順([`set_solve_value`])。
166    /// 多重構成の行(.zmx の CSP1・CSP2・TSP1〜TSP3・PSP1〜PSP3)。最適化の変数には使えない
167    CurvSolve(u8),
168    ThickSolve(u8),
169    ParmSolve(u8, u8),
170    /// 面の材料。多重構成の行(.zmx の GLSS)だけで、値は行の材料の名前の番号([`crate::configs::ConfigRow::names`])。
171    /// 最適化の変数には使えない
172    Material,
173    /// 面タイプのパラメータ(.zmx の PARM の番号、1 から)。ピックアップ・マクロのソルブの量(パラメータは
174    /// [`Kind::Asph`] などの意味のある名前で)
175    Parm(u8),
176    /// 面の前の傾き偏心の値 i(0〜4 = dx dy tx ty tz)。ピックアップの量(座標ブレークの面は [`Kind::Parm`]、
177    /// パラメータは [`Kind::Dx`] など)
178    Before(u8),
179    /// 面の後の傾き偏心の値 i(.zmx の SCBD 2 のピックアップ。元は [`Kind::Before`]、反転は倍率 −1)
180    After(u8),
181    /// 膜の名前。ピックアップ(倍率・オフセットは使わない。OpticStudio に無いので .zmx には書かない)と、多重構成の行
182    /// (.zmx の COTN。値は行の膜の名前の番号([`crate::configs::ConfigRow::names`])、空の名前は膜なし)。最適化の変数には使えない
183    Coating,
184    /// 利用者定義の形の面の設定の数の項目(名前、[`crate::usershape`])。名前は `u_<項目>`(面の番号と `.` で区切るので、項目の名前に `.` は使えない)
185    User(crate::usershape::UserKey),
186}
187
188impl Kind {
189    pub fn parse(s: &str) -> Result<Kind> {
190        if let Some(n) = s
191            .trim()
192            .strip_prefix("u_")
193            .filter(|n| !n.is_empty() && !n.contains('.'))
194        {
195            return match crate::usershape::UserKey::get(n) {
196                Some(k) => Ok(Kind::User(k)),
197                None => invalid!("no user-defined shape has the number setting {n}"),
198            };
199        }
200        let l = s.trim().to_ascii_lowercase();
201        Ok(match l.as_str() {
202            "c" | "curv" => Kind::Curv,
203            "r" | "radius" => Kind::Radius,
204            "k" | "conic" => Kind::Conic,
205            "t" | "thick" | "thickness" => Kind::Thick,
206            "dx" => Kind::Dx,
207            "dy" => Kind::Dy,
208            "tx" => Kind::Tx,
209            "ty" => Kind::Ty,
210            "tz" => Kind::Tz,
211            "dn" => Kind::Dn,
212            "disp" => Kind::Disp,
213            "objx" => Kind::ObjX,
214            "objy" => Kind::ObjY,
215            "semi" => Kind::Semi,
216            "ignore" => Kind::Ignore,
217            "apmax" => Kind::ApMax,
218            "material" => Kind::Material,
219            "apmin" => Kind::ApMin,
220            "apdx" => Kind::ApDx,
221            "apdy" => Kind::ApDy,
222            "aptype" => Kind::ApType,
223            "beforeorder" => Kind::BeforeOrder,
224            "afterorder" => Kind::AfterOrder,
225            "nd" => Kind::ModelNd,
226            "vd" => Kind::ModelVd,
227            "dpgf" => Kind::ModelDpgf,
228            "tce" => Kind::Tce,
229            "mech" => Kind::MechSemi,
230            "chip" => Kind::ChipZone,
231            "cror" => Kind::CoordRet,
232            "crsr" => Kind::CoordRetSurf,
233            "primary" => Kind::Primary,
234            "aper" => Kind::Aper,
235            "atype" => Kind::ApertureType,
236            "stop" => Kind::Stop,
237            "ftype" => Kind::FieldType,
238            "temp" => Kind::Temp,
239            "pres" => Kind::Pres,
240            "afocal" => Kind::Afocal,
241            "apodtype" => Kind::ApodType,
242            "apod" => Kind::Apod,
243            "aiming" => Kind::Aiming,
244            "ropd" => Kind::Ropd,
245            "pshx" => Kind::AimPupil(0),
246            "pshy" => Kind::AimPupil(1),
247            "pshz" => Kind::AimPupil(2),
248            "pscx" => Kind::AimPupil(3),
249            "pscy" => Kind::AimPupil(4),
250            "polun" => Kind::InputPol(0),
251            "poljx" => Kind::InputPol(1),
252            "poljy" => Kind::InputPol(2),
253            "polpx" => Kind::InputPol(3),
254            "polpy" => Kind::InputPol(4),
255            "coating" | "coat" => Kind::Coating,
256            _ => {
257                let num = |p: &str| l.strip_prefix(p).and_then(|n| n.parse::<u8>().ok());
258                if let Some(i) = num("before").filter(|&i| i < 5) {
259                    return Ok(Kind::Before(i));
260                }
261                if let Some(i) = num("after").filter(|&i| i < 5) {
262                    return Ok(Kind::After(i));
263                }
264                if let Some(i) = num("parm").or_else(|| num("p")) {
265                    return Ok(Kind::Parm(i));
266                }
267                if let Some(i) = num("csp").filter(|&i| (1..=2).contains(&i)) {
268                    return Ok(Kind::CurvSolve(i - 1));
269                }
270                if let Some(i) = num("tsp").filter(|&i| (1..=3).contains(&i)) {
271                    return Ok(Kind::ThickSolve(i - 1));
272                }
273                if let Some((i, n)) = l
274                    .strip_prefix("psp")
275                    .and_then(|r| r.split_once('_'))
276                    .and_then(|(i, n)| Some((i.parse::<u8>().ok()?, n.parse::<u8>().ok()?)))
277                    .filter(|&(i, n)| (1..=3).contains(&i) && n >= 1)
278                {
279                    return Ok(Kind::ParmSolve(n, i - 1));
280                }
281                for (j, pre) in VIG.iter().enumerate() {
282                    if let Some(n) = l.strip_prefix(pre).and_then(|v| v.parse::<u16>().ok()) {
283                        if (1..=256).contains(&n) {
284                            return Ok(Kind::FieldVig((n - 1) as u8, j as u8));
285                        }
286                    }
287                }
288                for (pre, f) in [
289                    ("wwt", Kind::WaveW as fn(u8) -> Kind),
290                    ("fx", Kind::FieldX),
291                    ("fy", Kind::FieldY),
292                    ("fwt", Kind::FieldW),
293                ] {
294                    if let Some(n) = l.strip_prefix(pre).and_then(|v| v.parse::<u16>().ok()) {
295                        if (1..=256).contains(&n) {
296                            return Ok(f((n - 1) as u8));
297                        }
298                    }
299                }
300                if let Some(n) = l.strip_prefix("wave").and_then(|v| v.parse::<u16>().ok()) {
301                    if (1..=256).contains(&n) {
302                        return Ok(Kind::Wave((n - 1) as u8));
303                    }
304                }
305                if let Some(n) = l.strip_prefix('z').and_then(|v| v.parse::<u16>().ok()) {
306                    if (1..=231).contains(&n) {
307                        return Ok(Kind::Zern(n));
308                    }
309                }
310                if let Some(n) = l.strip_prefix('a').and_then(|v| v.parse::<u8>().ok()) {
311                    if (2..=16).contains(&n) && n % 2 == 0 {
312                        return Ok(Kind::Asph(n / 2 - 1));
313                    }
314                }
315                invalid!("parameter type {s} (c r k a2..a16 z1..z231 t dx dy tx ty tz dn disp objx objy wave1.. wwt1.. primary aper fx1.. fy1.. fwt1.. u_<setting>, for pickups also semi p1.. before0..4 after0..4 coating)")
316            }
317        })
318    }
319
320    pub fn name(&self) -> String {
321        match self {
322            Kind::Curv => "c".into(),
323            Kind::Radius => "r".into(),
324            Kind::Conic => "k".into(),
325            Kind::Asph(i) => format!("a{}", 2 * (*i as usize + 1)),
326            Kind::Zern(j) => format!("z{j}"),
327            Kind::Thick => "t".into(),
328            Kind::Dx => "dx".into(),
329            Kind::Dy => "dy".into(),
330            Kind::Tx => "tx".into(),
331            Kind::Ty => "ty".into(),
332            Kind::Tz => "tz".into(),
333            Kind::Dn => "dn".into(),
334            Kind::Disp => "disp".into(),
335            Kind::ObjX => "objx".into(),
336            Kind::ObjY => "objy".into(),
337            Kind::Wave(i) => format!("wave{}", *i as usize + 1),
338            Kind::WaveW(i) => format!("wwt{}", *i as usize + 1),
339            Kind::Primary => "primary".into(),
340            Kind::Aper => "aper".into(),
341            Kind::ApertureType => "atype".into(),
342            Kind::Stop => "stop".into(),
343            Kind::FieldType => "ftype".into(),
344            Kind::Temp => "temp".into(),
345            Kind::Pres => "pres".into(),
346            Kind::Afocal => "afocal".into(),
347            Kind::ApodType => "apodtype".into(),
348            Kind::Apod => "apod".into(),
349            Kind::Aiming => "aiming".into(),
350            Kind::Ropd => "ropd".into(),
351            Kind::InputPol(i) => {
352                ["polun", "poljx", "poljy", "polpx", "polpy"][(*i as usize).min(4)].into()
353            }
354            Kind::AimPupil(i) => {
355                ["pshx", "pshy", "pshz", "pscx", "pscy"][(*i as usize).min(4)].into()
356            }
357            Kind::FieldX(i) => format!("fx{}", *i as usize + 1),
358            Kind::FieldY(i) => format!("fy{}", *i as usize + 1),
359            Kind::FieldW(i) => format!("fwt{}", *i as usize + 1),
360            Kind::FieldVig(i, j) => format!("{}{}", VIG[*j as usize], *i as usize + 1),
361            Kind::Unit(u) => u.name().into(),
362            Kind::Semi => "semi".into(),
363            Kind::Ignore => "ignore".into(),
364            Kind::ApMax => "apmax".into(),
365            Kind::Material => "material".into(),
366            Kind::ApMin => "apmin".into(),
367            Kind::ApDx => "apdx".into(),
368            Kind::ApDy => "apdy".into(),
369            Kind::ApType => "aptype".into(),
370            Kind::BeforeOrder => "beforeorder".into(),
371            Kind::AfterOrder => "afterorder".into(),
372            Kind::ModelNd => "nd".into(),
373            Kind::ModelVd => "vd".into(),
374            Kind::ModelDpgf => "dpgf".into(),
375            Kind::Tce => "tce".into(),
376            Kind::MechSemi => "mech".into(),
377            Kind::ChipZone => "chip".into(),
378            Kind::CoordRet => "cror".into(),
379            Kind::CoordRetSurf => "crsr".into(),
380            Kind::CurvSolve(i) => format!("csp{}", i + 1),
381            Kind::ThickSolve(i) => format!("tsp{}", i + 1),
382            Kind::ParmSolve(n, i) => format!("psp{}_{n}", i + 1),
383            Kind::Parm(i) => format!("p{i}"),
384            Kind::Before(i) => format!("before{i}"),
385            Kind::After(i) => format!("after{i}"),
386            Kind::Coating => "coating".into(),
387            Kind::User(k) => format!("u_{}", k.name()),
388        }
389    }
390}
391
392/// パラメータが付く先。面・玉/群の番号の意味は種類で変わらない
393#[derive(
394    Debug,
395    Clone,
396    Copy,
397    PartialEq,
398    Eq,
399    Hash,
400    serde::Serialize,
401    serde::Deserialize,
402    schemars::JsonSchema,
403)]
404#[serde(rename_all = "snake_case")]
405pub enum Target {
406    /// 面の番号
407    Surf(usize),
408    /// 玉・群の番号([`System::units`])
409    Unit(usize),
410    /// 面・玉・群に付かない系全体(物点の移動・波長)
411    System,
412}
413
414/// パラメータ: 付く先と種類。付く先は種類から決まる([`Kind::is_global`] は系全体、[`Kind::Unit`] は玉・群、
415/// ほかは面)ので、[`Param::new`]・[`Param::unit`]・[`Param::system`] で作る
416#[derive(
417    Debug,
418    Clone,
419    Copy,
420    PartialEq,
421    Eq,
422    Hash,
423    serde::Serialize,
424    serde::Deserialize,
425    schemars::JsonSchema,
426)]
427pub struct Param {
428    pub target: Target,
429    pub kind: Kind,
430}
431
432impl Param {
433    /// 面 surf のパラメータ kind(kind が系全体・玉/群の種類ならそちら。玉・群は surf が玉・群の番号)
434    pub fn new(surf: usize, kind: Kind) -> Param {
435        let target = if kind.is_global() {
436            Target::System
437        } else if kind.is_unit() {
438            Target::Unit(surf)
439        } else {
440            Target::Surf(surf)
441        };
442        Param { target, kind }
443    }
444    /// 系全体のパラメータ(物点の移動・波長)
445    pub fn system(kind: Kind) -> Param {
446        debug_assert!(kind.is_global());
447        Param {
448            target: Target::System,
449            kind,
450        }
451    }
452    pub fn obj_x() -> Param {
453        Param::system(Kind::ObjX)
454    }
455    pub fn obj_y() -> Param {
456        Param::system(Kind::ObjY)
457    }
458    /// 玉・群 u のパラメータ
459    pub fn unit(u: usize, kind: UnitKind) -> Param {
460        Param {
461            target: Target::Unit(u),
462            kind: Kind::Unit(kind),
463        }
464    }
465    /// 面の番号(面のパラメータでなければ None)
466    pub fn surface(&self) -> Option<usize> {
467        match self.target {
468            Target::Surf(j) => Some(j),
469            _ => None,
470        }
471    }
472    /// 玉・群の番号(玉・群のパラメータでなければ None)
473    pub fn unit_index(&self) -> Option<usize> {
474        match self.target {
475            Target::Unit(u) => Some(u),
476            _ => None,
477        }
478    }
479    /// 面・玉/群の番号(系全体は 0)。番号の意味は [`Self::target`] で決まる
480    pub fn index(&self) -> usize {
481        match self.target {
482            Target::Surf(j) | Target::Unit(j) => j,
483            Target::System => 0,
484        }
485    }
486    pub fn name(&self) -> String {
487        match self.target {
488            Target::System => self.kind.name(),
489            Target::Unit(u) => format!("unit{u}.{}", self.kind.name()),
490            Target::Surf(j) => format!("{j}.{}", self.kind.name()),
491        }
492    }
493}
494
495impl System {
496    /// パラメータを名前で: "3.t"、"L1 front.c"(面の名前.種類)、"objx"、"lens2.tx"(玉・群の名前.種類)。
497    /// `unit:` `surf:` を前に付けると玉・群か面かを決める
498    pub fn param(&self, spec: &str) -> Result<Param> {
499        let s = spec.trim();
500        if let Ok(k) = Kind::parse(s) {
501            if k.is_global() {
502                let p = Param::new(0, k);
503                self.check_param(p)?;
504                return Ok(p);
505            }
506        }
507        let Some((t, k)) = s.rsplit_once('.') else {
508            invalid!("parameter {s} (write surface.type, e.g. 3.t)");
509        };
510        let (t, force) = if let Some(x) = t.strip_prefix("unit:") {
511            (x, Some(true))
512        } else if let Some(x) = t.strip_prefix("surf:") {
513            (x, Some(false))
514        } else {
515            (t, None)
516        };
517        let unit = if force == Some(false) || t.trim().parse::<usize>().is_ok() {
518            None
519        } else {
520            self.find_unit(t)
521        };
522        if force == Some(true) && unit.is_none() {
523            invalid!("no lens or group named {}", t.trim());
524        }
525        if let Some(u) = unit {
526            if force.is_none() && self.find_surface(t).is_ok() {
527                let t = t.trim();
528                invalid!("{t} is the name of a surface and of a lens or group (write unit:{t}.{k} or surf:{t}.{k})");
529            }
530            let p = Param::unit(u, UnitKind::parse(k)?);
531            self.check_param(p)?;
532            return Ok(p);
533        }
534        let kind = Kind::parse(k)?;
535        let surf = self.find_surface(t)?;
536        let p = Param::new(surf, kind);
537        self.check_param(p)?;
538        Ok(p)
539    }
540
541    /// パラメータの名前(玉・群は名前で)
542    pub fn param_name(&self, p: Param) -> String {
543        match p.kind {
544            Kind::Unit(k) => match self.units.get(p.index()) {
545                Some(u) => format!("{}.{}", u.name, k.name()),
546                None => p.name(),
547            },
548            _ => p.name(),
549        }
550    }
551
552    /// パラメータがこの系で使えるか
553    pub fn check_param(&self, p: Param) -> Result<()> {
554        // 付く先は種類から決まる(読んだ JSON の食い違いを断る)
555        if Param::new(p.index(), p.kind) != p {
556            invalid!("parameter {}: the target doesn't match the kind", p.name());
557        }
558        if p.kind.is_pick_only() && !p.kind.is_table_only() {
559            invalid!("{} is a pickup quantity, not a parameter", p.kind.name());
560        }
561        if p.kind.is_object() {
562            return Ok(());
563        }
564        if let Kind::Wave(i) | Kind::WaveW(i) = p.kind {
565            if i as usize >= self.wavelengths.len() {
566                let (kind, nw) = (p.kind.name(), self.wavelengths.len());
567                invalid!("{kind} (there are {nw} wavelengths)");
568            }
569            return Ok(());
570        }
571        if let Kind::FieldX(i) | Kind::FieldY(i) | Kind::FieldW(i) | Kind::FieldVig(i, _) = p.kind {
572            if i as usize >= self.fields.len() {
573                let (kind, nf) = (p.kind.name(), self.fields.len());
574                invalid!("{kind} (there are {nf} field points)");
575            }
576            return Ok(());
577        }
578        if p.kind.is_system_value() {
579            return Ok(());
580        }
581        if let Kind::Unit(k) = p.kind {
582            let Some(u) = self.units.get(p.index()) else {
583                invalid!("lens or group {} ({} of them)", p.index(), self.units.len());
584            };
585            if matches!(k, UnitKind::Dn | UnitKind::Disp) && self.unit_media(p.index()).is_empty() {
586                let (unit, medium) = (&u.name, k.name());
587                invalid!("lens or group {unit} has no medium (glass) inside ({medium})");
588            }
589            return Ok(());
590        }
591        let Target::Surf(j) = p.target else {
592            invalid!("parameter {} is not on a surface", p.name());
593        };
594        if j >= self.surfaces.len() {
595            let last = self.surfaces.len() - 1;
596            invalid!("surface {j} (surfaces are 0 to {last})");
597        }
598        let d = &self.surfaces[j];
599        let curved = d.shape_params();
600        match p.kind {
601            Kind::Curv | Kind::Radius | Kind::Conic if j == 0 || !curved => {
602                invalid!("surface {j} ({:?}) {}", d.typ(), p.kind.name());
603            }
604            Kind::Asph(_) if !crate::pickup::takes_asph(d) => {
605                invalid!("surface {j} is not an even asphere ({})", p.kind.name());
606            }
607            Kind::Asph(i) if i >= 8 => invalid!("asphere coefficient {}", p.kind.name()),
608            Kind::Zern(n) => match &d.zern() {
609                Some(z) if (n as usize) <= crate::freeform::ZernSag::max_terms(z.fringe) => {}
610                Some(_) => invalid!("surface {j} Zernike term {n} is over the limit"),
611                None => invalid!(
612                    "surface {j} is not a Zernike Sag surface ({})",
613                    p.kind.name()
614                ),
615            },
616            _ => {}
617        }
618        // 形に効かない値(Tilted の c・k、Tilted の 3 番目からの asph など)は
619        // 変数・微分にしない
620        if let Kind::User(k) = p.kind {
621            if d.user_shape().and_then(|u| u.value(k.name())).is_none() {
622                let kind = p.kind.name();
623                invalid!("surface {j} is not a user-defined shape with the number setting {kind}");
624            }
625        }
626        if matches!(
627            p.kind,
628            Kind::Curv | Kind::Radius | Kind::Conic | Kind::Asph(_) | Kind::Zern(_) | Kind::User(_)
629        ) && !d.takes_shape_param(p.kind)
630        {
631            let (typ, kind) = (d.typ(), p.kind.name());
632            invalid!("surface {j} ({typ:?}): {kind} doesn't change the shape of this surface type");
633        }
634        match p.kind {
635            Kind::Dx | Kind::Dy | Kind::Tx | Kind::Ty | Kind::Tz if j == 0 => {
636                notimpl!("tilt or decenter of the object surface");
637            }
638            Kind::Dn | Kind::Disp if d.is_mirror() || d.is_coord_break() => {
639                let kind = p.kind.name();
640                invalid!("surface {j} is a mirror or a coordinate break (the medium is surface {kind} before it)");
641            }
642            Kind::Thick if j == self.image() => invalid!("thickness of the image surface"),
643            _ => {}
644        }
645        Ok(())
646    }
647
648    /// パラメータの今の値
649    pub fn get_param(&self, p: Param) -> Result<f64> {
650        self.check_param(p)?;
651        if p.kind.is_object() {
652            let kind = p.kind.name();
653            invalid!("field point {kind} is not system data (it is a trace input)");
654        }
655        match p.kind {
656            Kind::Wave(i) => return Ok(self.wavelengths[i as usize]),
657            Kind::WaveW(i) => return Ok(self.weights[i as usize]),
658            Kind::Primary => return Ok(self.primary as f64 + 1.0),
659            Kind::Aper => return Ok(self.aperture.1),
660            Kind::ApertureType => return Ok(self.aperture.0.os_code() as f64),
661            Kind::Stop => return Ok(self.stop() as f64),
662            Kind::FieldType => match self.field_type.os_code() {
663                Some(n) => return Ok(n as f64),
664                None => invalid!("a solved field type has no field type number"),
665            },
666            Kind::Temp => return Ok(self.temperature),
667            Kind::Pres => return Ok(self.pressure),
668            Kind::Afocal => return Ok(self.afocal as u8 as f64),
669            Kind::ApodType => return Ok(self.apodization.os_code() as f64),
670            Kind::Apod => return Ok(self.apodization.factor()),
671            Kind::Aiming => return Ok(self.aiming.os_code() as f64),
672            Kind::Ropd => return Ok(self.ropd as f64),
673            Kind::AimPupil(i) => return Ok(self.aim_pupil.value(i)),
674            Kind::InputPol(i) => return Ok(self.input_pol.value(i)),
675            Kind::FieldX(i) => return Ok(self.fields[i as usize].x),
676            Kind::FieldY(i) => return Ok(self.fields[i as usize].y),
677            Kind::FieldW(i) => return Ok(self.fields[i as usize].w),
678            Kind::FieldVig(i, j) => return Ok(*vig_mut(&mut self.fields[i as usize].clone(), j)),
679            _ => {}
680        }
681        if let Kind::Unit(k) = p.kind {
682            let u = &self.units[p.index()];
683            if let Some(i) = k.motion_index() {
684                return Ok(u.motion[i]);
685            }
686            return Ok(match k {
687                UnitKind::Shift => u.shift,
688                _ => {
689                    let v: Vec<f64> = self
690                        .unit_media(p.index())
691                        .iter()
692                        .map(|&j| {
693                            let d = &self.surfaces[j];
694                            if k == UnitKind::Dn {
695                                d.dn
696                            } else {
697                                d.disp
698                            }
699                        })
700                        .collect();
701                    if v.iter().any(|&x| x != v[0]) {
702                        let (unit, medium) = (&u.name, k.name());
703                        invalid!("lens or group {unit}: medium {medium} differs between surfaces ({v:?})");
704                    }
705                    v[0]
706                }
707            });
708        }
709        if p.kind.is_solve_value() {
710            return solve::get(self, p);
711        }
712        let d = &self.surfaces[p.index()];
713        Ok(match p.kind {
714            Kind::Curv => d.c,
715            Kind::Radius => {
716                if d.c == 0.0 {
717                    0.0
718                } else {
719                    1.0 / d.c
720                }
721            }
722            Kind::Conic => d.k,
723            Kind::Asph(i) => d.asph().get(i as usize).copied().unwrap_or(0.0),
724            Kind::Zern(n) => d
725                .zern()
726                .as_ref()
727                .and_then(|z| z.coef.get(n as usize - 1).copied())
728                .unwrap_or(0.0),
729            Kind::User(k) => d
730                .user_shape()
731                .and_then(|u| u.value(k.name()))
732                .unwrap_or(0.0),
733            Kind::Thick => d.t,
734            Kind::Semi => d.semi,
735            Kind::Ignore => f64::from(u8::from(d.ignore)),
736            Kind::Material => invalid!("{}: a material is a name, not a number", p.name()),
737            Kind::Coating => invalid!("{}: a coating is a name, not a number", p.name()),
738            Kind::ModelNd | Kind::ModelVd | Kind::ModelDpgf => match d.mat {
739                Material::Model { nd, vd, dpgf } => match p.kind {
740                    Kind::ModelNd => nd,
741                    Kind::ModelVd => vd,
742                    _ => dpgf,
743                },
744                _ => invalid!("{}: surface material is not a model glass", p.name()),
745            },
746            Kind::Tce => d.tce,
747            Kind::MechSemi => self.lens_radius(p.index()),
748            Kind::ChipZone => d.chip_zone,
749            Kind::CoordRet => d.coord_return.map_or(0.0, |c| c.mode.os_code() as f64),
750            Kind::CoordRetSurf => d.coord_return.map_or(0.0, |c| c.surf as f64),
751            Kind::ApMax => match d.ap {
752                Aperture::Circular { max, .. } | Aperture::Obsc { max, .. } => max,
753                _ => invalid!(
754                    "{}: surface has no circular aperture or obscuration",
755                    p.name()
756                ),
757            },
758            Kind::ApMin => match d.ap {
759                Aperture::Circular { min, .. } | Aperture::Obsc { min, .. } => min,
760                _ => invalid!(
761                    "{}: surface has no circular aperture or obscuration",
762                    p.name()
763                ),
764            },
765            Kind::ApDx | Kind::ApDy => match aperture_decenter(&d.ap) {
766                Some((dx, dy)) => {
767                    if p.kind == Kind::ApDx {
768                        dx
769                    } else {
770                        dy
771                    }
772                }
773                None => invalid!("{}: surface has no aperture", p.name()),
774            },
775            Kind::ApType => aperture_os_code(&d.ap) as f64,
776            Kind::Before(i) => d.before.map_or(0.0, |t| t.d[i as usize]),
777            Kind::BeforeOrder => d.before.map_or(0.0, |t| f64::from(t.order)),
778            Kind::After(i) => match d.after {
779                After::Tilt(t) => t.d[i as usize],
780                After::None => 0.0,
781                After::Reverse => invalid!(
782                    "{}: the tilt and decenter after the surface reverses the one before",
783                    p.name()
784                ),
785            },
786            Kind::AfterOrder => match d.after {
787                After::Tilt(t) => f64::from(t.order),
788                After::None => 0.0,
789                After::Reverse => invalid!(
790                    "{}: the tilt and decenter after the surface reverses the one before",
791                    p.name()
792                ),
793            },
794            Kind::Dn => d.dn,
795            Kind::Disp => d.disp,
796            k => {
797                let i = k.tilt_index().expect("tilt kind");
798                if d.is_coord_break() {
799                    d.cb()[i]
800                } else {
801                    d.before.map(|b| b.d[i]).unwrap_or(0.0)
802                }
803            }
804        })
805    }
806
807    /// パラメータを変える。影響しないキャッシュ(座標系・近軸量)は残す
808    pub fn set_param(&mut self, p: Param, v: f64) -> Result<()> {
809        self.set_params(&[(p, v)])
810    }
811
812    /// まとめて変える(キャッシュの捨て方も 1 回で決める)。エラーのときは系を変えない
813    pub fn set_params(&mut self, changes: &[(Param, f64)]) -> Result<()> {
814        *self = self.with_params(changes)?;
815        Ok(())
816    }
817
818    /// 複製してパラメータを変える(元の系のキャッシュのうち影響しないものを引き継ぐ)
819    /// 自動の半直径も求め直す
820    pub fn with_params(&self, changes: &[(Param, f64)]) -> Result<System> {
821        let mut s = self.with_params_solve(changes, true)?;
822        s.update_semi();
823        Ok(s)
824    }
825
826    /// [`System::with_params`] で、自動の半直径を求め直さない(最適化・公差の差分など、半直径を使わない繰り返し用。
827    /// 半直径は光線の追跡に効かない)
828    pub fn with_params_fast(&self, changes: &[(Param, f64)]) -> Result<System> {
829        let mut s = self.with_params_solve(changes, true)?;
830        if s.semi_affects_trace() {
831            s.update_semi();
832        }
833        Ok(s)
834    }
835
836    /// [`System::with_params`]。solve が false ならソルブを解き直さない(ソルブの微分の差分用)
837    pub(crate) fn with_params_solve(
838        &self,
839        changes: &[(Param, f64)],
840        solve: bool,
841    ) -> Result<System> {
842        let (flat, motions, picked) = self.unit_changes(changes)?;
843        let mut keep = keep_for(&flat);
844        if !motions.is_empty() {
845            keep.frames = false;
846        }
847        let mut s = self.clone_keep(keep);
848        s.apply(&flat)?;
849        for &(u, k, v) in &motions {
850            let x = &mut s.rx_mut().units[u];
851            match k.motion_index() {
852                Some(i) => x.motion[i] = v,
853                None => x.shift = v,
854            }
855        }
856        // ピックアップで決まる先は、展開した値と合っているか確かめる(倍率・オフセットが玉・群の動きと合わない)
857        for &(p, v) in &picked {
858            let now = s.get_param(p)?;
859            if (now - v).abs() > 1e-12 * (1.0 + v.abs()) {
860                let name = p.name();
861                invalid!("{name} becomes {now} by a pickup and doesn't match {v} of the lens or group change");
862            }
863        }
864        // 傾き・偏心だけの変更で近軸量を残せて、ソルブが近軸量と面の形・厚さだけで決まり既に解けていれば、
865        // 解き直さない(解き直すと座標系などのキャッシュを捨てる)
866        let any = !s.solves.is_empty() || !s.macro_parms.is_empty();
867        if solve && any && !(keep.paraxial && s.macro_parms.is_empty() && s.solves_still_hold()) {
868            s.solve_thickness()?;
869        }
870        if flat.iter().any(|(p, _)| p.index() == 0) {
871            s.check()?;
872        }
873        Ok(s)
874    }
875
876    /// 玉・群のパラメータの変更を、面のパラメータの変更と、玉・群の動き・移動の値の更新に分ける。
877    /// 3 つ目は、ピックアップ先なので変更から除いた面のパラメータと、なるべき値
878    #[allow(clippy::type_complexity)]
879    fn unit_changes(
880        &self,
881        changes: &[(Param, f64)],
882    ) -> Result<(
883        Vec<(Param, f64)>,
884        Vec<(usize, UnitKind, f64)>,
885        Vec<(Param, f64)>,
886    )> {
887        if !changes.iter().any(|(p, _)| p.kind.is_unit()) {
888            return Ok((changes.to_vec(), Vec::new(), Vec::new()));
889        }
890        // 3 つ目は玉・群から展開した変更か
891        let mut flat: Vec<(Param, f64, bool)> = Vec::new();
892        let mut motions = Vec::new();
893        // 移動の厚さの変化は、同じ面に重なれば足す(隣り合う範囲の間の間隔など)
894        let mut shifted: Vec<(usize, f64)> = Vec::new();
895        let mut shift_at: Option<usize> = None;
896        for &(p, v) in changes {
897            let Kind::Unit(k) = p.kind else {
898                flat.push((p, v, false));
899                continue;
900            };
901            self.check_param(p)?;
902            if !v.is_finite() {
903                invalid!("{} = {v}", self.param_name(p));
904            }
905            match k {
906                UnitKind::Shift => {
907                    let d = v - self.units[p.index()].shift;
908                    for (q, f) in self.unit_terms(p, false)? {
909                        match shifted.iter_mut().find(|x| x.0 == q.index()) {
910                            Some(x) => x.1 += f * d,
911                            None => shifted.push((q.index(), f * d)),
912                        }
913                    }
914                    shift_at.get_or_insert(flat.len());
915                    motions.push((p.index(), k, v));
916                }
917                UnitKind::Dn | UnitKind::Disp => {
918                    for (q, _) in self.unit_terms(p, false)? {
919                        flat.push((q, v, true));
920                    }
921                }
922                _ => motions.push((p.index(), k, v)),
923            }
924        }
925        if let Some(at) = shift_at {
926            let th: Vec<(Param, f64, bool)> = shifted
927                .iter()
928                .filter(|x| x.1 != 0.0)
929                .map(|&(j, d)| (Param::new(j, Kind::Thick), self.surfaces[j].t + d, true))
930                .collect();
931            flat.splice(at..at, th);
932        }
933        // ピックアップ先で、元も変える面は除く(ピックアップで追従する)
934        let mut picked = Vec::new();
935        let srcs: Vec<Param> = flat.iter().map(|x| x.0).collect();
936        flat.retain(|&(p, v, gen)| match self.pickup_of(p) {
937            Some(pk)
938                if gen
939                    && srcs.iter().any(|q| {
940                        q.index() == pk.src
941                            && pick_kind(&self.surfaces[q.index()], q.kind) == Some(pk.what)
942                    }) =>
943            {
944                picked.push((p, v));
945                false
946            }
947            _ => true,
948        });
949        Ok((
950            flat.into_iter().map(|(p, v, _)| (p, v)).collect(),
951            motions,
952            picked,
953        ))
954    }
955
956    /// 玉・群の shift・dn・disp を、面のパラメータの組合せ(パラメータ, 係数)にする。
957    /// shift: 範囲ごとに前の間隔 +1・後の間隔 −1(無限遠の物体距離・厚さのソルブの面・ピックアップ先で元も
958    /// 組合せに入る面は除く)。dn・disp: 範囲の中の媒質ごとに +1
959    pub(crate) fn unit_linear(&self, p: Param) -> Result<Vec<(Param, f64)>> {
960        self.unit_terms(p, true)
961    }
962
963    /// unit_linear の中身。drop_picked が false ならピックアップ先も残す(変更では後で確かめる)
964    fn unit_terms(&self, p: Param, drop_picked: bool) -> Result<Vec<(Param, f64)>> {
965        let Kind::Unit(k) = p.kind else {
966            return Ok(vec![(p, 1.0)]);
967        };
968        let u = &self.units[p.index()];
969        let mut out: Vec<(Param, f64)> = Vec::new();
970        match k {
971            UnitKind::Shift => {
972                let mut add = |j: usize, f: f64| match out.iter_mut().find(|x| x.0.index() == j) {
973                    Some(x) => x.1 += f,
974                    None => out.push((Param::new(j, Kind::Thick), f)),
975                };
976                for s in &u.spans {
977                    add(s[0] - 1, 1.0);
978                    add(s[1], -1.0);
979                }
980                out.retain(|(q, f)| {
981                    *f != 0.0
982                        && self.surfaces[q.index()].t.is_finite()
983                        && !self.solves.iter().any(|x| x.surf == q.index())
984                });
985                if drop_picked {
986                    let all: Vec<usize> = out.iter().map(|x| x.0.index()).collect();
987                    out.retain(|(q, _)| match self.pickup_of(*q) {
988                        Some(pk) => !all.contains(&pk.src),
989                        None => true,
990                    });
991                }
992            }
993            UnitKind::Dn | UnitKind::Disp => {
994                let kind = if k == UnitKind::Dn {
995                    Kind::Dn
996                } else {
997                    Kind::Disp
998                };
999                for j in self.unit_media(p.index()) {
1000                    out.push((Param::new(j, kind), 1.0));
1001                }
1002            }
1003            _ => out.push((p, 1.0)),
1004        }
1005        Ok(out)
1006    }
1007
1008    /// 値を書き換える(キャッシュはそのまま)。残してよいキャッシュを返す
1009    fn apply(&mut self, changes: &[(Param, f64)]) -> Result<Keep> {
1010        // 書き換える前にすべて確かめる(途中で止まって半端に変わった系を残さない)
1011        for &(p, v) in changes {
1012            self.check_param(p)?;
1013            if p.kind.is_object() {
1014                let kind = p.kind.name();
1015                invalid!("field point {kind} is not system data (it is a trace input)");
1016            }
1017            if !v.is_finite() && !(p.kind == Kind::Thick && p.index() == 0) {
1018                invalid!("{} = {v}", p.name());
1019            }
1020            if p.kind.is_wave() {
1021                if !(v > 0.0) {
1022                    invalid!("{} = {v} µm", p.name());
1023                }
1024                continue;
1025            }
1026            if p.kind.is_solve_value() {
1027                solve::check(self, p, v)?;
1028            }
1029            match p.kind {
1030                Kind::Primary
1031                    if v.fract() != 0.0 || v < 1.0 || v > self.wavelengths.len() as f64 =>
1032                {
1033                    invalid!("primary wavelength {v} (1 to {})", self.wavelengths.len());
1034                }
1035                Kind::WaveW(_) | Kind::FieldW(_) if v < 0.0 => invalid!("{} = {v}", p.name()),
1036                Kind::Aper if !(v > 0.0) => invalid!("aperture value {v}"),
1037                Kind::ApertureType
1038                    if v.fract() != 0.0 || ApertureKind::from_os_code(v as i64).is_none() =>
1039                {
1040                    invalid!("aperture type {v} (0 to 5)");
1041                }
1042                Kind::Semi if v < 0.0 => invalid!("{} = {v}", p.name()),
1043                Kind::Ignore if v != 0.0 && v != 1.0 => invalid!("{} = {v} (0 or 1)", p.name()),
1044                Kind::ApMax if v < 0.0 => invalid!("{} = {v}", p.name()),
1045                Kind::Material => invalid!("{}: a material is a name, not a number", p.name()),
1046                Kind::Coating => invalid!("{}: a coating is a name, not a number", p.name()),
1047                Kind::ModelNd | Kind::ModelVd | Kind::ModelDpgf
1048                    if !matches!(self.surfaces[p.index()].mat, Material::Model { .. }) =>
1049                {
1050                    invalid!("{}: surface material is not a model glass", p.name())
1051                }
1052                Kind::ModelNd if !(v > 0.0) => invalid!("{} = {v}", p.name()),
1053                Kind::ApMin | Kind::MechSemi | Kind::ChipZone if !(v >= 0.0) => {
1054                    invalid!("{} = {v}", p.name())
1055                }
1056                Kind::CoordRet | Kind::CoordRetSurf => crate::coord_return::check(self, p, v)?,
1057                Kind::BeforeOrder | Kind::AfterOrder if v != 0.0 && v != 1.0 => {
1058                    invalid!("{} = {v} (0 or 1)", p.name())
1059                }
1060                Kind::ApType if v.fract() != 0.0 || !(0.0..=2.0).contains(&v) => {
1061                    invalid!("{}: aperture type {v} (0 to 2 can be set)", p.name())
1062                }
1063                Kind::ApType
1064                    if v != 0.0
1065                        && !matches!(
1066                            self.surfaces[p.index()].ap,
1067                            Aperture::Circular { .. } | Aperture::Obsc { .. }
1068                        ) =>
1069                {
1070                    invalid!(
1071                        "{}: surface has no circular aperture or obscuration (its radii are kept)",
1072                        p.name()
1073                    )
1074                }
1075                Kind::ApMin
1076                    if !matches!(
1077                        self.surfaces[p.index()].ap,
1078                        Aperture::Circular { .. } | Aperture::Obsc { .. }
1079                    ) =>
1080                {
1081                    invalid!(
1082                        "{}: surface has no circular aperture or obscuration",
1083                        p.name()
1084                    )
1085                }
1086                Kind::ApDx | Kind::ApDy
1087                    if aperture_decenter(&self.surfaces[p.index()].ap).is_none() =>
1088                {
1089                    invalid!("{}: surface has no aperture", p.name())
1090                }
1091                Kind::Before(_) | Kind::BeforeOrder | Kind::After(_) | Kind::AfterOrder
1092                    if self.surfaces[p.index()].is_coord_break() =>
1093                {
1094                    invalid!(
1095                        "{}: a coordinate break has no surface tilt or decenter",
1096                        p.name()
1097                    )
1098                }
1099                Kind::After(_) | Kind::AfterOrder
1100                    if self.surfaces[p.index()].after == After::Reverse =>
1101                {
1102                    invalid!(
1103                        "{}: the tilt and decenter after the surface reverses the one before",
1104                        p.name()
1105                    )
1106                }
1107                Kind::ApMax
1108                    if !matches!(
1109                        self.surfaces[p.index()].ap,
1110                        Aperture::Circular { .. } | Aperture::Obsc { .. }
1111                    ) =>
1112                {
1113                    invalid!(
1114                        "{}: surface has no circular aperture or obscuration",
1115                        p.name()
1116                    )
1117                }
1118                Kind::Ignore if p.index() == 0 || p.index() + 1 >= self.surfaces.len() => {
1119                    invalid!(
1120                        "{}: the object and image surfaces can't be ignored",
1121                        p.name()
1122                    );
1123                }
1124                Kind::FieldType
1125                    if v.fract() != 0.0
1126                        || crate::system::FieldType::from_os_code(v as i64).is_none() =>
1127                {
1128                    invalid!("field type {v} (0 to 3)");
1129                }
1130                Kind::Pres if v < 0.0 => invalid!("pressure {v} atm"),
1131                Kind::Temp if v < -273.15 => invalid!("temperature {v} °C"),
1132                Kind::Afocal if v != 0.0 && v != 1.0 => invalid!("{} = {v} (0 or 1)", p.name()),
1133                Kind::ApodType if v.fract() != 0.0 || !(0.0..=2.0).contains(&v) => {
1134                    invalid!("apodization type {v} (0 to 2)");
1135                }
1136                Kind::Apod if v < 0.0 => invalid!("apodization factor {v}"),
1137                Kind::Aiming if v.fract() != 0.0 || !(0.0..=2.0).contains(&v) => {
1138                    invalid!("ray aiming {v} (0 to 2)");
1139                }
1140                Kind::Ropd if v.fract() != 0.0 || !(0.0..=3.0).contains(&v) => {
1141                    invalid!("OPD reference {v} (0 to 3)");
1142                }
1143                Kind::Stop
1144                    if v.fract() != 0.0 || v < 1.0 || v > self.surfaces.len() as f64 - 2.0 =>
1145                {
1146                    let last = self.surfaces.len() - 2;
1147                    invalid!("stop surface {v} (1 to {last})");
1148                }
1149                _ => {}
1150            }
1151            if p.kind.is_system_value() {
1152                continue;
1153            }
1154            let solved = |k: Kind| {
1155                self.solves
1156                    .iter()
1157                    .find(|q| q.surf == p.index() && q.kind.param_kind() == k)
1158            };
1159            let q = match p.kind {
1160                Kind::Thick => solved(Kind::Thick),
1161                Kind::Curv | Kind::Radius => solved(Kind::Curv),
1162                _ => None,
1163            };
1164            if let Some(q) = q {
1165                invalid!(
1166                    "{} is set by a solve ({})",
1167                    p.name(),
1168                    solve_kind_info(q.kind).0
1169                );
1170            }
1171            if let Some(pk) = self.pickup_of(p) {
1172                let (name, src, scale, offset) = (p.name(), pk.src, pk.scale, pk.offset);
1173                invalid!("{name} is a pickup from surface {src} (scale {scale}, offset {offset}); change the source surface");
1174            }
1175        }
1176        let mut index = false;
1177        // 波長は先に変える(屈折率は元の系の値の作り方に合わせて作り直す)
1178        let waves: Vec<(usize, f64)> = changes
1179            .iter()
1180            .filter_map(|&(p, v)| match p.kind {
1181                Kind::Wave(i) => Some((i as usize, v)),
1182                _ => None,
1183            })
1184            .collect();
1185        if !waves.is_empty() {
1186            self.set_wavelengths(&waves)?;
1187            index = true;
1188        }
1189        for &(p, v) in changes {
1190            let rx = self.rx_mut();
1191            match p.kind {
1192                Kind::Wave(_) => continue,
1193                Kind::WaveW(i) => rx.weights[i as usize] = v,
1194                Kind::Primary => rx.primary = v as usize - 1,
1195                Kind::Aper => rx.aperture.1 = v,
1196                Kind::ApertureType => {
1197                    // 番号は上で確かめた
1198                    if let Some(k) = ApertureKind::from_os_code(v as i64) {
1199                        rx.aperture.0 = k;
1200                    }
1201                }
1202                Kind::FieldType => {
1203                    // 番号は上で確かめた
1204                    if let Some(t) = crate::system::FieldType::from_os_code(v as i64) {
1205                        rx.field_type = t;
1206                    }
1207                }
1208                Kind::Stop => {
1209                    for (j, d) in rx.surfaces.iter_mut().enumerate() {
1210                        d.stop = j == v as usize;
1211                    }
1212                }
1213                Kind::Temp => {
1214                    rx.temperature = v;
1215                    index = true;
1216                }
1217                Kind::Pres => {
1218                    rx.pressure = v;
1219                    index = true;
1220                }
1221                Kind::Afocal => rx.afocal = v != 0.0,
1222                // 種類を変えてから係数(同じ変更の中の順によらない)
1223                Kind::ApodType => {
1224                    let g = changes
1225                        .iter()
1226                        .find(|(q, _)| q.kind == Kind::Apod)
1227                        .map_or(rx.apodization.factor(), |c| c.1);
1228                    rx.apodization = Apodization::from_os_code(v as i64, g);
1229                }
1230                Kind::Apod => {
1231                    if let Apodization::Gaussian(g) = &mut rx.apodization {
1232                        *g = v;
1233                    }
1234                }
1235                Kind::Aiming => rx.aiming = Aiming::from_os_code(v as i64),
1236                Kind::Ropd => rx.ropd = v as i64,
1237                Kind::AimPupil(i) => rx.aim_pupil.set(i, v),
1238                Kind::InputPol(i) => rx.input_pol.set(i, v),
1239                Kind::FieldX(i) => rx.fields[i as usize].x = v,
1240                Kind::FieldY(i) => rx.fields[i as usize].y = v,
1241                Kind::FieldW(i) => rx.fields[i as usize].w = v,
1242                Kind::FieldVig(i, j) => *vig_mut(&mut rx.fields[i as usize], j) = v,
1243                _ => {}
1244            }
1245            if p.kind.is_system_value() {
1246                continue;
1247            }
1248            if p.kind.is_solve_value() {
1249                solve::set_solve_value(self.rx_mut(), p, v);
1250                continue;
1251            }
1252            let d = &mut self.rx_mut().surfaces[p.index()];
1253            match p.kind {
1254                Kind::Curv => d.c = v,
1255                Kind::Radius => d.c = if v == 0.0 { 0.0 } else { 1.0 / v },
1256                Kind::Conic => d.k = v,
1257                Kind::Asph(i) => {
1258                    let i = i as usize;
1259                    if let Some(a) = d.asph_mut().filter(|a| a.len() <= i) {
1260                        a.resize(8, 0.0);
1261                    }
1262                    d.set_asph_at(i, v);
1263                }
1264                Kind::Zern(n) => {
1265                    let z = std::sync::Arc::make_mut(
1266                        d.zern_mut().and_then(|z| z.as_mut()).expect("Zernike data"),
1267                    );
1268                    let i = n as usize - 1;
1269                    if z.coef.len() <= i {
1270                        z.coef.resize(i + 1, 0.0);
1271                    }
1272                    z.coef[i] = v;
1273                    z.rebuild();
1274                }
1275                Kind::User(k) => {
1276                    let slot = d.user_shape_mut().expect("user-defined shape");
1277                    let u = slot
1278                        .as_ref()
1279                        .expect("user-defined shape")
1280                        .with_value(k.name(), v)?;
1281                    *slot = Some(u);
1282                }
1283                Kind::Thick => d.t = v,
1284                Kind::Semi => {
1285                    d.semi = v;
1286                    d.semi_auto = false;
1287                    // 浮動開口は面の半直径でける
1288                    if let Aperture::Floating { semi } = &mut d.ap {
1289                        *semi = v;
1290                    }
1291                }
1292                Kind::Ignore => d.ignore = v != 0.0,
1293                // 上で断った
1294                Kind::Material | Kind::Coating => {}
1295                Kind::ModelNd | Kind::ModelVd | Kind::ModelDpgf => {
1296                    set_surface_table_value(d, p.kind, v);
1297                    index = true;
1298                }
1299                Kind::ApMax => {
1300                    if let Aperture::Circular { max, .. } | Aperture::Obsc { max, .. } = &mut d.ap {
1301                        *max = v;
1302                    }
1303                }
1304                Kind::ApMin
1305                | Kind::ApDx
1306                | Kind::ApDy
1307                | Kind::ApType
1308                | Kind::Before(_)
1309                | Kind::BeforeOrder
1310                | Kind::After(_)
1311                | Kind::AfterOrder
1312                | Kind::Tce
1313                | Kind::MechSemi
1314                | Kind::ChipZone
1315                | Kind::CoordRet
1316                | Kind::CoordRetSurf => {
1317                    set_surface_table_value(d, p.kind, v);
1318                }
1319                Kind::Dn => {
1320                    d.dn = v;
1321                    index = true;
1322                }
1323                Kind::Disp => {
1324                    d.disp = v;
1325                    index = true;
1326                }
1327                k => {
1328                    let i = k.tilt_index().expect("tilt kind");
1329                    if let Some((cb, _)) = d.cb_mut() {
1330                        cb[i] = v;
1331                    } else {
1332                        // 前の傾き偏心がなければ作り、面の後は「前を戻す」にする(その面だけが動く)。
1333                        // 既にあれば面の後はそのまま(後ろの面も一緒に動く系もある)
1334                        if d.before.is_none() {
1335                            d.before = Some(Tilt {
1336                                d: [0.0; 5],
1337                                order: 0,
1338                            });
1339                            if d.after == After::None {
1340                                d.after = After::Reverse;
1341                            }
1342                        }
1343                        d.before.as_mut().expect("coordinate break created above").d[i] = v;
1344                    }
1345                }
1346            }
1347        }
1348        if !self.pickups.is_empty() {
1349            self.resolve_pickups()?;
1350        }
1351        if index {
1352            self.resolve_media()?;
1353        }
1354        // 座標の戻りは、前の面の形が変われば傾き・偏心・厚さを求め直す(厚さが変われば近軸量も変わる)
1355        let cr = changes.iter().any(|(p, _)| p.kind.is_coord_return());
1356        if crate::coord_return::resolve_changed(self.rx_mut())? || cr {
1357            return Ok(Keep {
1358                frames: false,
1359                paraxial: false,
1360            });
1361        }
1362        Ok(keep_for(changes))
1363    }
1364}
1365
1366/// けられ係数の名前([`Kind::FieldVig`] の j の順)
1367const VIG: [&str; 5] = ["vdx", "vdy", "vcx", "vcy", "van"];
1368
1369/// 視野 f のけられ係数 j(0〜4 = VDX・VDY・VCX・VCY・VAN)
1370fn vig_mut(f: &mut crate::system::Field, j: u8) -> &mut f64 {
1371    match j {
1372        0 => &mut f.vdx,
1373        1 => &mut f.vdy,
1374        2 => &mut f.vcx,
1375        3 => &mut f.vcy,
1376        _ => &mut f.van,
1377    }
1378}