Skip to main content

lensbench_core/
usershape.rs

1//! 利用者が定義する形の面の口(面の種類 [`crate::surface::SurfType::UserShape`])。
2//!
3//! 面の形は、土台の二次曲面(面の曲率 c・円錐係数 k)に、登録したモデルの矢高を足したもの。働きはふつうの屈折・
4//! 反射で、材料・膜・偏光の追跡はほかの面と同じように効く(形は法線を通してだけ効く)。曲げ方と位相だけを
5//! 決める利用者定義の面([`crate::usersurf`]、種類 USER)とは別の口。
6//!
7//! [`ShapeModel`] を実装して拡張の表([`crate::ext::Ext::add_shape_model`])に足し、種類 USERSHAPE の面に
8//! `shape = {"model": 名前, "config": {…}}`([`UserShape`])を与える。設定は検出器・解析のプラグインと同じ
9//! 数・文字列・数の並びの小さな辞書([`crate::plugin::Config`])。
10//!
11//! 約束([`check_shape`] で確かめられる):
12//! - [`ShapeInstance::sag`] は面の局所座標 (x, y) で、土台に足す矢高と勾配 (z, ∂z/∂x, ∂z/∂y) を返す。状態を
13//!   持たず、どのスレッドから呼んでもよい。クリア半径の少し外(交点のニュートン法が通る所)まで有限で、
14//!   勾配は連続(着地点の微分は勾配の差分で 2 階を求める)。面が無い所は NaN(その光線は落ちる)
15//! - [`ShapeInstance::dsag`] は設定の数の項目(名前)による (z, ∂z/∂x, ∂z/∂y) の微分。返す項目は変数・
16//!   微分(dOPL/dp・着地点の微分)にでき、パラメータの種類は [`crate::param::Kind::User`](`u_<名前>`)。
17//!   値を変えるときは設定のその項目を書き換えて [`ShapeModel::prepare`] で作り直すので、prepare は軽くする
18//!   (重い前処理はモデルの中で使い回す)
19//! - 鏡の後に置く・玉を反転するときの裏返しは core が包む(z → −z は矢高の符号、x → −x は x の向き)。
20//!   モデルは何もしなくてよい
21//! - 近軸の曲率(EFL・瞳など)は、土台の c に、頂点での矢高の 2 階(YZ 面、勾配の中心差分。幅はクリア半径の
22//!   1e-6)を足したもの。近軸は YZ 面だけで、XZ 面の曲率は見ない(ほかの回転対称でない面と同じ)
23//! - [`ShapeInstance::phase`] を返すモデルは、面の上の位相 Φ [rad] も持つ(回折・メタ面)。扱いは Binary 2 と同じ: 屈折・
24//!   反射の後に回折の式で向きを変え(Φ の勾配 × λ/2π を接線の成分に足す)、光路長に λ/2π · Φ を足す(λ はレンズの単位)。
25//!   電場は方向の変化と同じ最小の回転で回す。近軸は頂点での ∂²Φ/∂y²(勾配の中心差分)を屈折力に足す。回折次数・波長に
26//!   よらない位相(rad)を返し、次数を変えたいときは設定に持つ。裏返し(z)では変えず、x の映しは x の向きを替える。
27//!   dOPL/dp・着地点の微分はこの面を通る光線では未対応(Binary 2 と同じく誤り)
28//! - [`ShapeInstance::jones`] を返すモデルは、偏光の追跡で膜の係数(と位相の回折)の後に位置ごとの Jones 行列をかける
29//!   (基底は Jones 面と同じ、[`crate::trace::apply_jones`])。z の裏返しでは変えず、x の映しは B・C の符号を替える
30//! - .zmx には書けない(系ファイル・プロジェクトには書ける)
31
32use std::collections::HashSet;
33use std::sync::{Arc, OnceLock, RwLock};
34
35use crate::plugin::{Config, ParamSpec, Value};
36use crate::{invalid, Result, RwLockExt};
37
38/// 利用者定義の形のモデル(設定から [`ShapeInstance`] を作る)
39pub trait ShapeModel: Send + Sync {
40    /// 登録の名前
41    fn name(&self) -> &str;
42    /// 1 行の説明
43    fn doc(&self) -> String {
44        String::new()
45    }
46    /// 設定の項目(GUI の欄・一覧用)
47    fn params(&self) -> Vec<ParamSpec> {
48        Vec::new()
49    }
50    /// 設定を確かめて形を作る(軽くする。最適化・公差では値を変えるたびに呼ぶ)
51    fn prepare(&self, config: &Config) -> Result<Arc<dyn ShapeInstance>>;
52    /// 試しの設定(拡張の検査で [`check_shape`] に渡す)。既定は [`ShapeModel::params`] の既定値を並べたもの
53    /// (既定値の無い項目があれば None。そのときは自分で返す)
54    fn example_config(&self) -> Option<Config> {
55        self.params()
56            .into_iter()
57            .map(|p| Some((p.name, p.default?)))
58            .collect()
59    }
60    /// 試しの設定で確かめる半径 [mm](形が有効な半直径。既定 10)
61    fn example_radius(&self) -> f64 {
62        10.0
63    }
64}
65
66/// 準備した形
67pub trait ShapeInstance: Send + Sync {
68    /// 土台の二次曲面に足す矢高と勾配 (z, ∂z/∂x, ∂z/∂y)(面の局所座標)
69    fn sag(&self, x: f64, y: f64) -> (f64, f64, f64);
70    /// 設定の数の項目 `key` による (z, ∂z/∂x, ∂z/∂y) の微分。None はその項目では微分できない(変数にできない)
71    fn dsag(&self, key: &str, x: f64, y: f64) -> Option<[f64; 3]> {
72        let _ = (key, x, y);
73        None
74    }
75    /// 面の上の位相と勾配 (Φ [rad], ∂Φ/∂x, ∂Φ/∂y)(面の局所座標)。None は位相なし(既定)。頂点 (0, 0) で
76    /// None を返すモデルは位相を持たないとみなし、ほかの点でも呼ばない
77    fn phase(&self, x: f64, y: f64) -> Option<(f64, f64, f64)> {
78        let _ = (x, y);
79        None
80    }
81    /// 面の局所座標 (x, y) と波長 [µm] での Jones 行列 [A, B, C, D](Ex' = A·Ex + B·Ey、Ey' = C·Ex + D·Ey)。膜の
82    /// 係数(屈折・反射)の後にかける。基底は Jones 面と同じく、局所の ±z を出射の向きへ移す最小の回転で運んだ
83    /// x・y。None は Jones なし(既定)。頂点 (0, 0)・0.55 µm で None を返すモデルは Jones を持たないとみなす
84    fn jones(&self, x: f64, y: f64, wl_um: f64) -> Option<[crate::coating::C64; 4]> {
85        let _ = (x, y, wl_um);
86        None
87    }
88}
89
90/// 面に付ける利用者定義の形(モデルの名前・設定・裏返しの向きと、準備した形)。系ファイルには名前・設定・向きを
91/// 書き、読むときに登録から作り直す
92#[derive(Clone, serde::Serialize, serde::Deserialize)]
93#[serde(try_from = "UserShapeSpec", into = "UserShapeSpec")]
94pub struct UserShape {
95    pub model: String,
96    pub config: Config,
97    /// z について裏返した(矢高の符号が逆)
98    pub flip_z: bool,
99    /// x について映した(x の向きが逆)
100    pub mirror_x: bool,
101    inst: Arc<dyn ShapeInstance>,
102    /// 位相を持つ(頂点で [`ShapeInstance::phase`] が Some)
103    has_phase: bool,
104}
105
106/// [`UserShape`] の書き出しの形
107#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
108pub(crate) struct UserShapeSpec {
109    /// モデルの名前
110    pub model: String,
111    /// 設定(数・文字列・数の並び)
112    #[serde(default)]
113    pub config: Config,
114    /// z について裏返した(鏡の後・玉の反転。矢高の符号が逆)
115    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
116    pub flip_z: bool,
117    /// x について映した(玉の反転。x の向きが逆)
118    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
119    pub mirror_x: bool,
120}
121
122impl TryFrom<UserShapeSpec> for UserShape {
123    type Error = crate::Error;
124    fn try_from(s: UserShapeSpec) -> Result<Self> {
125        let mut u = UserShape::new(&s.model, s.config)?;
126        u.flip_z = s.flip_z;
127        u.mirror_x = s.mirror_x;
128        Ok(u)
129    }
130}
131
132impl From<UserShape> for UserShapeSpec {
133    fn from(u: UserShape) -> Self {
134        UserShapeSpec {
135            model: u.model,
136            config: u.config,
137            flip_z: u.flip_z,
138            mirror_x: u.mirror_x,
139        }
140    }
141}
142
143impl schemars::JsonSchema for UserShape {
144    fn schema_name() -> std::borrow::Cow<'static, str> {
145        UserShapeSpec::schema_name()
146    }
147    fn json_schema(g: &mut schemars::SchemaGenerator) -> schemars::Schema {
148        UserShapeSpec::json_schema(g)
149    }
150}
151
152impl std::fmt::Debug for UserShape {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        f.debug_struct("UserShape")
155            .field("model", &self.model)
156            .field("config", &self.config)
157            .field("flip_z", &self.flip_z)
158            .field("mirror_x", &self.mirror_x)
159            .finish()
160    }
161}
162
163impl PartialEq for UserShape {
164    fn eq(&self, o: &Self) -> bool {
165        self.model == o.model
166            && self.config == o.config
167            && self.flip_z == o.flip_z
168            && self.mirror_x == o.mirror_x
169    }
170}
171
172impl UserShape {
173    /// 今の拡張の表([`crate::ext::current`])のモデル `model` を設定 `config` で準備する(裏返しなし)
174    pub fn new(model: &str, config: Config) -> Result<UserShape> {
175        let m = crate::ext::current().shape_model(model)?;
176        let inst = m.prepare(&config)?;
177        for (k, v) in &config {
178            if matches!(v, Value::Num(_)) {
179                UserKey::intern(k);
180            }
181        }
182        let has_phase = inst.phase(0.0, 0.0).is_some();
183        Ok(UserShape {
184            model: model.to_string(),
185            config,
186            flip_z: false,
187            mirror_x: false,
188            inst,
189            has_phase,
190        })
191    }
192
193    /// 準備した形(裏返しを含まない、モデルが返したまま)
194    pub fn instance(&self) -> &dyn ShapeInstance {
195        self.inst.as_ref()
196    }
197
198    fn signs(&self) -> (f64, f64) {
199        (
200            if self.flip_z { -1.0 } else { 1.0 },
201            if self.mirror_x { -1.0 } else { 1.0 },
202        )
203    }
204
205    /// 裏返しを含めた、土台に足す矢高と勾配
206    #[inline]
207    pub fn sag(&self, x: f64, y: f64) -> (f64, f64, f64) {
208        let (s, m) = self.signs();
209        let (z, zx, zy) = self.inst.sag(m * x, y);
210        (s * z, s * m * zx, s * zy)
211    }
212
213    /// 裏返しを含めた、項目 `key` による微分([`ShapeInstance::dsag`])
214    pub fn dsag(&self, key: &str, x: f64, y: f64) -> Option<[f64; 3]> {
215        let (s, m) = self.signs();
216        let d = self.inst.dsag(key, m * x, y)?;
217        Some([s * d[0], s * m * d[1], s * d[2]])
218    }
219
220    /// 位相を持つか([`ShapeInstance::phase`])
221    pub fn has_phase(&self) -> bool {
222        self.has_phase
223    }
224
225    /// 裏返しを含めた位相と勾配(位相を持たなければ None)。z の裏返しでは変えず、x の映しは x の向きを替える
226    #[inline]
227    pub fn phase(&self, x: f64, y: f64) -> Option<(f64, f64, f64)> {
228        if !self.has_phase {
229            return None;
230        }
231        let (_, m) = self.signs();
232        let (p, px, py) = self.inst.phase(m * x, y)?;
233        Some((p, m * px, py))
234    }
235
236    /// Jones を持つか(頂点・0.55 µm で [`ShapeInstance::jones`] が Some)
237    pub fn has_jones(&self) -> bool {
238        self.inst.jones(0.0, 0.0, 0.55).is_some()
239    }
240
241    /// 裏返しを含めた Jones 行列: z の裏返しでは変えず、x の映しは映した点の行列の B・C の符号を替える
242    pub fn jones(&self, x: f64, y: f64, wl_um: f64) -> Option<[crate::coating::C64; 4]> {
243        let (_, m) = self.signs();
244        let j = self.inst.jones(m * x, y, wl_um)?;
245        Some(if self.mirror_x {
246            [j[0], -j[1], -j[2], j[3]]
247        } else {
248            j
249        })
250    }
251
252    /// 頂点での位相の 2 階 ∂²Φ/∂y² [rad/mm²](近軸の屈折力に足す分。幅 h の勾配の中心差分)。位相なしは 0
253    pub fn paraxial_dphi(&self, h: f64) -> f64 {
254        match (self.phase(0.0, h), self.phase(0.0, -h)) {
255            (Some(a), Some(b)) => (a.2 - b.2) / (2.0 * h),
256            _ => 0.0,
257        }
258    }
259
260    /// 設定の数の項目 `key` の値(無い・数(`Num`)でなければ None。数の並びは変数にできない)
261    pub fn value(&self, key: &str) -> Option<f64> {
262        match self.config.get(key)? {
263            Value::Num(v) => Some(*v),
264            _ => None,
265        }
266    }
267
268    /// 項目 `key` を値 `v` にして作り直したもの(向きはそのまま)
269    pub fn with_value(&self, key: &str, v: f64) -> Result<UserShape> {
270        let mut config = self.config.clone();
271        config.insert(key.to_string(), Value::Num(v));
272        let mut u = UserShape::new(&self.model, config)?;
273        u.flip_z = self.flip_z;
274        u.mirror_x = self.mirror_x;
275        Ok(u)
276    }
277
278    /// 頂点での矢高の 2 階 ∂²z/∂y²(近軸の曲率に足す分。幅 h [mm] の勾配の中心差分、[`paraxial_step`])
279    pub fn paraxial_curv(&self, h: f64) -> f64 {
280        let (_, _, a) = self.sag(0.0, h);
281        let (_, _, b) = self.sag(0.0, -h);
282        (a - b) / (2.0 * h)
283    }
284}
285
286/// 登録したモデルが [`ShapeModel::params`] で宣言した数の項目の名前を、パラメータの名前の表に足す(拡張の表に
287/// 足すときに呼ぶ。パラメータ `u_<項目>` を、その項目を持つ形を準備する前に読めるように)
288pub(crate) fn declare(m: &dyn ShapeModel) {
289    for p in m.params() {
290        if p.ty == crate::plugin::ParamType::Num && !p.name.is_empty() && !p.name.contains('.') {
291            UserKey::intern(&p.name);
292        }
293    }
294}
295
296/// 近軸の曲率を求める差分の幅 [mm]: クリア半径の 1e-6(半径が決まっていなければ 1e-5 mm)
297pub fn paraxial_step(semi: f64) -> f64 {
298    if semi > 0.0 && semi.is_finite() {
299        1e-6 * semi
300    } else {
301        1e-5
302    }
303}
304
305/// 利用者定義の形の項目の名前([`crate::param::Kind::User`])。`Kind` を Copy のまま名前で持つため、名前をプロセスの
306/// 表に 1 つだけ置いた文字列への参照にしたもの(光線ごとの微分で表を引かない)。表に足すのは準備できた形の設定の
307/// 数の項目だけ(外から来た誤った名前で増えない)。serde・表示は名前の文字列。
308///
309/// 登録したモデルが [`ShapeModel::params`] で宣言した数の項目は、形を準備する前(系より先に変数の行を読むときなど)
310/// から読める:
311///
312/// ```
313/// use lensbench_core::param::Kind;
314/// use lensbench_core::plugin::{Config, ParamSpec, ParamType};
315/// use lensbench_core::usershape::{ShapeInstance, ShapeModel};
316/// use std::sync::Arc;
317///
318/// struct Bump;
319/// impl ShapeModel for Bump {
320///     fn name(&self) -> &str { "doc_bump" }
321///     fn params(&self) -> Vec<ParamSpec> {
322///         vec![ParamSpec::new("height", ParamType::Num, None, "mm", "")]
323///     }
324///     fn prepare(&self, _: &Config) -> lensbench_core::Result<Arc<dyn ShapeInstance>> {
325///         unimplemented!()
326///     }
327/// }
328///
329/// // 新しいプロセスで、形を何も準備していないうちは読めない
330/// assert!(Kind::parse("u_height").is_err());
331/// let mut ext = lensbench_core::ext::Ext::default();
332/// ext.add_shape_model(Arc::new(Bump));
333/// assert!(Kind::parse("u_height").is_ok());
334/// // 宣言していない名前は表に足さない
335/// assert!(Kind::parse("u_nothing").is_err());
336/// ```
337#[derive(Debug, Clone, Copy)]
338pub struct UserKey(&'static str);
339
340impl PartialEq for UserKey {
341    fn eq(&self, o: &Self) -> bool {
342        // 表に 1 つだけ置くので、同じ名前は同じ場所
343        std::ptr::eq(self.0, o.0)
344    }
345}
346impl Eq for UserKey {}
347impl std::hash::Hash for UserKey {
348    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
349        (self.0.as_ptr() as usize).hash(h)
350    }
351}
352impl PartialOrd for UserKey {
353    fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
354        Some(self.cmp(o))
355    }
356}
357impl Ord for UserKey {
358    fn cmp(&self, o: &Self) -> std::cmp::Ordering {
359        self.0.cmp(o.0)
360    }
361}
362
363fn names() -> &'static RwLock<HashSet<&'static str>> {
364    static N: OnceLock<RwLock<HashSet<&'static str>>> = OnceLock::new();
365    N.get_or_init(Default::default)
366}
367
368impl UserKey {
369    /// 表にある名前(登録したモデルが宣言した項目と、準備した形の設定の数の項目)。無ければ None。
370    /// 読むとき(serde)も同じ表を引く:
371    ///
372    /// ```
373    /// use lensbench_core::plugin::{Config, ParamSpec, ParamType};
374    /// use lensbench_core::usershape::{ShapeInstance, ShapeModel, UserKey};
375    /// use std::sync::Arc;
376    ///
377    /// struct Tilt;
378    /// impl ShapeModel for Tilt {
379    ///     fn name(&self) -> &str { "doc_tilt" }
380    ///     fn params(&self) -> Vec<ParamSpec> {
381    ///         vec![ParamSpec::new("slope", ParamType::Num, None, "", "")]
382    ///     }
383    ///     fn prepare(&self, _: &Config) -> lensbench_core::Result<Arc<dyn ShapeInstance>> {
384    ///         unimplemented!()
385    ///     }
386    /// }
387    ///
388    /// // 新しいプロセスで、登録の前は読めない
389    /// assert!(serde_json::from_str::<UserKey>("\"slope\"").is_err());
390    /// lensbench_core::ext::Ext::default().add_shape_model(Arc::new(Tilt));
391    /// let k: UserKey = serde_json::from_str("\"slope\"").unwrap();
392    /// assert_eq!((k.name(), UserKey::get("slope")), ("slope", Some(k)));
393    /// assert!(serde_json::from_str::<UserKey>("\"nothing\"").is_err());
394    /// ```
395    pub fn get(name: &str) -> Option<UserKey> {
396        names().read_ok().get(name).map(|&n| UserKey(n))
397    }
398
399    /// 名前を表に足す(初めての名前だけ。登録したモデルが宣言した項目と、準備できた形の設定の項目から呼ぶ)
400    fn intern(name: &str) -> UserKey {
401        if let Some(k) = UserKey::get(name) {
402            return k;
403        }
404        let mut n = names().write_ok();
405        if let Some(&s) = n.get(name) {
406            return UserKey(s);
407        }
408        let s: &'static str = Box::leak(name.to_string().into_boxed_str());
409        n.insert(s);
410        UserKey(s)
411    }
412
413    /// 名前
414    pub fn name(&self) -> &'static str {
415        self.0
416    }
417}
418
419impl serde::Serialize for UserKey {
420    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
421        s.serialize_str(self.name())
422    }
423}
424
425impl<'de> serde::Deserialize<'de> for UserKey {
426    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
427        let s = String::deserialize(d)?;
428        UserKey::get(&s).ok_or_else(|| {
429            serde::de::Error::custom(format!("no user-defined shape has the number setting {s}"))
430        })
431    }
432}
433
434impl schemars::JsonSchema for UserKey {
435    fn schema_name() -> std::borrow::Cow<'static, str> {
436        "UserKey".into()
437    }
438    fn json_schema(g: &mut schemars::SchemaGenerator) -> schemars::Schema {
439        String::json_schema(g)
440    }
441}
442
443/// モデルが約束を守るかを確かめる(拡張の試験から呼ぶ)。半径 `radius` の 1.2 倍の円の内の格子の点で:
444/// - 矢高・勾配が有限
445/// - 勾配が矢高の中心差分と合う
446/// - [`ShapeInstance::dsag`] を返す項目は、設定のその項目を少し変えて作り直した矢高・勾配の中心差分と合う
447/// - 位相を持つ(頂点で [`ShapeInstance::phase`] が Some)なら、同じ点で位相が有限で、勾配が位相の中心差分と合う
448pub fn check_shape(model: &dyn ShapeModel, config: &Config, radius: f64) -> Result<()> {
449    let name = model.name();
450    if !(radius > 0.0 && radius.is_finite()) {
451        invalid!("check_shape: radius must be positive ({radius})");
452    }
453    let base = model.prepare(config)?;
454    let r = 1.2 * radius;
455    let n = 7;
456    let pts: Vec<(f64, f64)> = (0..n)
457        .flat_map(|i| (0..n).map(move |j| (i, j)))
458        .map(|(i, j)| {
459            let t = |k: usize| -r + 2.0 * r * k as f64 / (n - 1) as f64;
460            (t(i), t(j))
461        })
462        // 円(半径の 1.2 倍)の内だけ
463        .filter(|&(x, y)| x * x + y * y <= r * r * (1.0 + 1e-12))
464        .collect();
465    let h = 1e-6 * radius;
466    for &(x, y) in &pts {
467        let (z, zx, zy) = base.sag(x, y);
468        if !(z.is_finite() && zx.is_finite() && zy.is_finite()) {
469            invalid!("user-defined shape model {name}: the sag is not finite at ({x}, {y}) (inside 1.2 × radius)");
470        }
471        let nx = (base.sag(x + h, y).0 - base.sag(x - h, y).0) / (2.0 * h);
472        let ny = (base.sag(x, y + h).0 - base.sag(x, y - h).0) / (2.0 * h);
473        let tol = |a: f64| 1e-5 * (1.0 + a.abs());
474        if (nx - zx).abs() > tol(zx) || (ny - zy).abs() > tol(zy) {
475            invalid!("user-defined shape model {name}: the gradient ({zx}, {zy}) at ({x}, {y}) does not match the difference of the sag ({nx}, {ny})");
476        }
477        if base.phase(0.0, 0.0).is_some() {
478            let ph = |x: f64, y: f64| base.phase(x, y).map(|p| p.0).unwrap_or(f64::NAN);
479            let fin = |p: &(f64, f64, f64)| p.0.is_finite() && p.1.is_finite() && p.2.is_finite();
480            let Some((_, px, py)) = base.phase(x, y).filter(fin) else {
481                invalid!("user-defined shape model {name}: the phase is not finite at ({x}, {y}) (inside 1.2 × radius)");
482            };
483            let nx = (ph(x + h, y) - ph(x - h, y)) / (2.0 * h);
484            let ny = (ph(x, y + h) - ph(x, y - h)) / (2.0 * h);
485            let tol = |a: f64| 1e-5 * (1.0 + a.abs());
486            if !((nx - px).abs() <= tol(px) && (ny - py).abs() <= tol(py)) {
487                invalid!("user-defined shape model {name}: the phase gradient ({px}, {py}) at ({x}, {y}) does not match the difference of the phase ({nx}, {ny})");
488            }
489        }
490    }
491    for (key, v) in config {
492        let v0 = match v {
493            Value::Num(v) => *v,
494            _ => continue,
495        };
496        if base.dsag(key, 0.0, 0.0).is_none() {
497            continue;
498        }
499        let dv = 1e-6 * (1.0 + v0.abs());
500        let at = |val: f64| -> Result<Arc<dyn ShapeInstance>> {
501            let mut c = config.clone();
502            c.insert(key.clone(), Value::Num(val));
503            model.prepare(&c)
504        };
505        let (p, m) = (at(v0 + dv)?, at(v0 - dv)?);
506        for &(x, y) in &pts {
507            let Some(d) = base.dsag(key, x, y) else {
508                invalid!("user-defined shape model {name}: dsag of {key} is given at the vertex but not at ({x}, {y})");
509            };
510            let (a, b) = (p.sag(x, y), m.sag(x, y));
511            let num = [
512                (a.0 - b.0) / (2.0 * dv),
513                (a.1 - b.1) / (2.0 * dv),
514                (a.2 - b.2) / (2.0 * dv),
515            ];
516            for i in 0..3 {
517                if (num[i] - d[i]).abs() > 1e-4 * (1.0 + d[i].abs()) {
518                    invalid!("user-defined shape model {name}: dsag of {key} at ({x}, {y}) is {d:?} but the difference of the sag gives {num:?}");
519                }
520            }
521        }
522    }
523    Ok(())
524}