1use crate::montecarlo::{Dist, GroupTol, LensTol};
5use crate::term_spec::RefName;
6use indexmap::IndexMap;
7use schemars::JsonSchema;
8use serde::de::{Deserializer, Error as _};
9use serde::Deserialize;
10use serde_json::Value;
11
12macro_rules! via_value {
14 ($t:ty, $f:expr) => {
15 impl<'de> Deserialize<'de> for $t {
16 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
17 let v = Value::deserialize(d)?;
18 let f: fn(Value) -> lensbench_core::Result<$t> = $f;
19 f(v).map_err(|e| D::Error::custom(String::from(e)))
20 }
21 }
22 };
23}
24
25fn from<T: serde::de::DeserializeOwned>(v: Value) -> lensbench_core::Result<T> {
27 lensbench_project::lenient::from_json(&v, "").map_err(|e| {
28 let m = e.message().unwrap_or_default();
29 m.strip_prefix(": ")
30 .or_else(|| m.strip_prefix('.'))
31 .unwrap_or(m)
32 .to_string()
33 .into()
34 })
35}
36
37#[derive(Deserialize, JsonSchema, Debug, Clone, Default)]
39#[serde(deny_unknown_fields)]
40pub struct TolSpec {
41 #[serde(rename = "$schema")]
43 pub schema: Option<String>,
44 pub trials: Option<usize>,
46 pub seed: Option<u64>,
48 pub dist: Option<Dist>,
50 pub radial: Option<Radial>,
52 pub preset: Option<String>,
54 pub wedge_face: Option<Face>,
56 pub catalog: Option<bool>,
58 pub catalog_tols: Option<IndexMap<String, Option<CatEntry>>>,
60 pub lenses: Option<IndexMap<String, Option<LensEntry>>>,
62 pub groups: Option<IndexMap<String, Option<GroupTol>>>,
64 pub tols: Option<Vec<TolItem>>,
66 pub compensators: Option<Compensators>,
68 pub comp_iters: Option<usize>,
70 pub comp_mode: Option<CompModeName>,
73 pub inverse: Option<InverseSpec>,
75 pub merit: Option<MeritName>,
77 pub rings: Option<usize>,
79 pub reference: Option<RefName>,
80 pub terms: Option<Value>,
82 pub sensitivity: Option<bool>,
84 pub percentiles: Option<Vec<f64>>,
86 pub samples: Option<bool>,
88 pub threads: Option<usize>,
90}
91
92#[derive(Deserialize, JsonSchema, Debug, Clone, Copy, PartialEq)]
94#[serde(rename_all = "lowercase")]
95pub enum CompModeName {
96 Optimize,
98 Paraxial,
100 None,
102}
103
104#[derive(Deserialize, JsonSchema, Debug, Clone, Default)]
106#[serde(deny_unknown_fields)]
107pub struct InverseSpec {
108 pub limit: Option<f64>,
110 pub increment: Option<f64>,
112 pub skip: Option<Vec<String>>,
114 pub rtol: Option<f64>,
116}
117
118#[derive(Deserialize, JsonSchema, Debug, Clone, Copy, PartialEq)]
120#[serde(rename_all = "lowercase")]
121pub enum Face {
122 Back,
124 Front,
126}
127
128#[derive(Deserialize, JsonSchema, Debug, Clone, Copy, PartialEq)]
130#[serde(rename_all = "lowercase")]
131pub enum MeritName {
132 Wavefront,
133 Spot,
134 None,
136}
137
138#[derive(JsonSchema, Debug, Clone)]
140#[schemars(untagged)]
141pub enum Radial {
142 On(bool),
143 Dist(String),
144}
145via_value!(Radial, |v| match v {
146 Value::Bool(b) => Ok(Radial::On(b)),
147 Value::String(s) => Ok(Radial::Dist(s)),
148 x => Err(format!("radial must be true, false, uniform, normal or normal:σ ({x})").into()),
149});
150
151macro_rules! lens_fields {
152 ($(#[$m:meta])* $name:ident { $($(#[$em:meta])* $ek:ident: $et:ty,)* }) => {
153 $(#[$m])*
154 #[derive(Deserialize, JsonSchema, Debug, Clone, Default)]
155 #[serde(deny_unknown_fields)]
156 pub struct $name {
157 pub radius_rel: Option<f64>,
159 pub focal_rel: Option<f64>,
161 pub thickness: Option<f64>,
163 pub wedge: Option<f64>,
165 pub wedge_face: Option<Face>,
166 pub dn: Option<f64>,
168 pub disp: Option<f64>,
170 pub decenter: Option<f64>,
172 pub tilt: Option<f64>,
174 pub space: Option<f64>,
176 $($(#[$em])* pub $ek: $et,)*
177 }
178
179 impl $name {
180 pub fn apply(&self, base: LensTol) -> LensTol {
182 let o = |x: Option<f64>, d: f64| x.unwrap_or(d);
183 LensTol {
184 radius_rel: o(self.radius_rel, base.radius_rel),
185 focal_rel: o(self.focal_rel, base.focal_rel),
186 thickness: o(self.thickness, base.thickness),
187 wedge: o(self.wedge, base.wedge),
188 dn: o(self.dn, base.dn),
189 disp: o(self.disp, base.disp),
190 decenter: o(self.decenter, base.decenter),
191 tilt: o(self.tilt, base.tilt),
192 space: o(self.space, base.space),
193 wedge_first: self.wedge_face.map_or(base.wedge_first, |f| f == Face::Front),
194 }
195 }
196 }
197 };
198}
199
200lens_fields!(
201 LensFields {}
203);
204
205lens_fields!(
206 CatFields {
208 rules: Option<Vec<Rule>>,
210 }
211);
212
213lens_fields!(
214 Rule {
216 dia_lt: Option<f64>,
218 dia_le: Option<f64>,
219 dia_gt: Option<f64>,
220 dia_ge: Option<f64>,
221 efl_lt: Option<f64>,
223 efl_le: Option<f64>,
224 efl_gt: Option<f64>,
225 efl_ge: Option<f64>,
226 cemented: Option<bool>,
228 }
229);
230
231impl Rule {
232 pub fn matches(&self, dia: f64, efl: f64, glasses: usize) -> bool {
234 let e = efl.abs();
235 let c = |x: Option<f64>, f: &dyn Fn(f64) -> bool| x.is_none_or(f);
236 c(self.dia_lt, &|l| dia < l)
237 && c(self.dia_le, &|l| dia <= l)
238 && c(self.dia_gt, &|l| dia > l)
239 && c(self.dia_ge, &|l| dia >= l)
240 && c(self.efl_lt, &|l| e < l)
241 && c(self.efl_le, &|l| e <= l)
242 && c(self.efl_gt, &|l| e > l)
243 && c(self.efl_ge, &|l| e >= l)
244 && self.cemented.is_none_or(|k| k == (glasses >= 2))
245 }
246
247 pub fn fields(&self) -> LensFields {
249 LensFields {
250 radius_rel: self.radius_rel,
251 focal_rel: self.focal_rel,
252 thickness: self.thickness,
253 wedge: self.wedge,
254 wedge_face: self.wedge_face,
255 dn: self.dn,
256 disp: self.disp,
257 decenter: self.decenter,
258 tilt: self.tilt,
259 space: self.space,
260 }
261 }
262}
263
264#[derive(JsonSchema, Debug, Clone)]
266#[schemars(untagged)]
267pub enum LensEntry {
268 Preset(String),
269 Fields(LensFields),
270}
271via_value!(LensEntry, |v| match v {
272 Value::String(s) => Ok(LensEntry::Preset(s)),
273 v @ Value::Object(_) => from(v).map(LensEntry::Fields),
274 x => Err(format!("an object, a set name or null ({x})").into()),
275});
276
277#[derive(JsonSchema, Debug, Clone)]
279#[schemars(untagged)]
280pub enum CatEntry {
281 Preset(String),
282 Fields(CatFields),
283}
284via_value!(CatEntry, |v| match v {
285 Value::String(s) => Ok(CatEntry::Preset(s)),
286 v @ Value::Object(_) => from(v).map(CatEntry::Fields),
287 x => Err(format!("an object, a set name or null ({x})").into()),
288});
289
290pub fn preset(name: &str, base: LensTol) -> lensbench_core::Result<LensTol> {
292 LensTol::preset(name).map(|t| LensTol {
293 wedge_first: base.wedge_first,
294 ..t
295 })
296}
297
298impl LensEntry {
299 pub fn apply(&self, base: LensTol) -> lensbench_core::Result<LensTol> {
300 match self {
301 LensEntry::Preset(p) => preset(p, base),
302 LensEntry::Fields(f) => Ok(f.apply(base)),
303 }
304 }
305}
306
307#[derive(Deserialize, JsonSchema, Debug, Clone)]
309#[serde(deny_unknown_fields)]
310pub struct TolItem {
311 pub param: Option<String>,
313 pub params: Option<Vec<String>>,
315 pub pm: Option<f64>,
317 pub lo: Option<f64>,
318 pub hi: Option<f64>,
319 pub relative: Option<bool>,
321 pub dist: Option<Dist>,
322 pub label: Option<String>,
323 pub scale: Option<Vec<f64>>,
325}
326
327#[derive(JsonSchema, Debug, Clone)]
329#[schemars(untagged)]
330pub enum VarSpec {
331 Text(String),
332 Obj(VarObj),
333}
334via_value!(VarSpec, |v| match v {
335 Value::String(s) => Ok(VarSpec::Text(s)),
336 v @ Value::Object(_) => from(v).map(VarSpec::Obj),
337 x => Err(format!("a compensator must be a string or an object ({x})").into()),
338});
339
340#[derive(Deserialize, JsonSchema, Debug, Clone)]
342#[serde(deny_unknown_fields)]
343pub struct VarObj {
344 pub param: String,
345 pub lo: Option<f64>,
346 pub hi: Option<f64>,
347 pub configs: Option<Vec<usize>>,
349}
350
351#[derive(JsonSchema, Debug, Clone)]
353#[schemars(untagged)]
354pub enum Compensators {
355 One(VarSpec),
356 Many(Vec<VarSpec>),
357}
358via_value!(Compensators, |v| match v {
359 Value::Array(a) => a
360 .into_iter()
361 .map(from)
362 .collect::<Result<_, _>>()
363 .map(Compensators::Many),
364 v => from(v).map(Compensators::One),
365});
366
367impl Compensators {
368 pub fn list(&self) -> Vec<&VarSpec> {
369 match self {
370 Compensators::One(v) => vec![v],
371 Compensators::Many(a) => a.iter().collect(),
372 }
373 }
374}