1use crate::step::StepSize;
12use lensbench_project::UserItem;
13use serde_json::{json, Value};
14
15pub const FILLABLE: [&str; 2] = ["thickness", "diameter"];
17
18#[derive(Debug, Clone, PartialEq)]
20pub struct Reading {
21 pub name: &'static str,
23 pub label: String,
25 pub raw: String,
27 pub value: Option<Value>,
29}
30
31#[derive(Debug, Clone, Default, PartialEq)]
33pub struct PageRead {
34 pub thickness: Option<f64>,
36 pub diameter: Option<Value>,
38 pub mount_thickness: Option<f64>,
40 pub mount_diameter: Option<f64>,
41 pub clear_aperture: Option<f64>,
42 pub found: Vec<Reading>,
44}
45
46impl PageRead {
47 pub fn get(&self, name: &str) -> Option<Value> {
49 match name {
50 "thickness" => self.thickness.map(|x| json!(x)),
51 "diameter" => self.diameter.clone(),
52 "mount_thickness" => self.mount_thickness.map(|x| json!(x)),
53 "mount_diameter" => self.mount_diameter.map(|x| json!(x)),
54 "clear_aperture" => self.clear_aperture.map(|x| json!(x)),
55 _ => None,
56 }
57 }
58}
59
60const MAX_TEXT: usize = 4 << 20;
62
63fn label_kind(label: &str) -> Option<(&'static str, u8)> {
65 let l = label
66 .trim()
67 .trim_end_matches(':')
68 .trim()
69 .to_ascii_lowercase();
70 if l.is_empty() || l.len() > 48 {
72 return None;
73 }
74 let head0 = l.split('(').next().unwrap_or("").trim();
76 let frame = match head0 {
77 "mount thickness" | "housing thickness" | "mounted thickness" | "mount thickness t" => {
78 Some(("mount_thickness", 0))
79 }
80 "mount diameter"
81 | "mount outer diameter"
82 | "housing diameter"
83 | "mounted diameter"
84 | "housing outer diameter"
85 | "mount od" => Some(("mount_diameter", 0)),
86 "clear aperture" | "clear aperture ca" | "ca" => Some(("clear_aperture", 0)),
87 _ => None,
88 };
89 if let Some(f) = frame {
90 return (head0.len() == l.len() || l[head0.len()..].trim_start().starts_with('('))
91 .then_some(f);
92 }
93 let bad = [
94 "mount",
95 "housing",
96 "tolerance",
97 "cell",
98 "edge thickness",
99 "total",
100 "frame",
101 "clear aperture",
102 "beam",
103 "minor",
104 "major",
105 "wedge",
106 "coating",
107 "ring",
108 "thread",
109 ];
110 if bad.iter().any(|b| l.contains(b)) {
111 return None;
112 }
113 let head = l.split('(').next().unwrap_or("").trim();
114 let t = match head {
115 "thickness" | "substrate thickness" | "thickness t" => Some(("thickness", 0)),
116 "center thickness" | "center thickness ct" | "ct" => Some(("thickness", 1)),
117 "diameter" | "outer diameter" | "diameter d" | "outside diameter" => Some(("diameter", 0)),
118 "dimensions" | "size" | "dimension" => Some(("diameter", 1)),
119 _ => None,
120 };
121 t.filter(|_| head.len() == l.len() || l[head.len()..].trim_start().starts_with('('))
123}
124
125fn unit_scale(label: &str, raw: &str) -> f64 {
127 let l = label.to_ascii_lowercase();
128 if l.contains("(mm)") || l.contains("mm)") {
129 return 1.0;
130 }
131 if l.contains("(in") || l.contains("inch") {
132 return 25.4;
133 }
134 let r = raw.to_ascii_lowercase();
135 if r.contains("mm") {
136 1.0
137 } else if r.contains('"') || r.contains("inch") || inch_after_number(&r) {
138 25.4
139 } else {
140 1.0
141 }
142}
143
144fn inch_after_number(r: &str) -> bool {
146 let b = r.as_bytes();
147 numbers(r).iter().any(|&(st, _)| {
148 let mut i = st;
149 while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') {
150 i += 1;
151 }
152 while i < b.len() && b[i] == b' ' {
153 i += 1;
154 }
155 b[i..].starts_with(b"in") && b.get(i + 2).is_none_or(|c| !c.is_ascii_alphabetic())
156 })
157}
158
159fn numbers(s: &str) -> Vec<(usize, f64)> {
161 let b = s.as_bytes();
162 let mut out = Vec::new();
163 let mut i = 0;
164 while i < b.len() {
165 if b[i].is_ascii_digit() || (b[i] == b'.' && i + 1 < b.len() && b[i + 1].is_ascii_digit()) {
166 let st = i;
167 while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') {
168 i += 1;
169 }
170 if let Ok(x) = s[st..i].trim_end_matches('.').parse::<f64>() {
171 out.push((st, x));
172 }
173 } else {
174 i += 1;
175 }
176 }
177 out
178}
179
180fn parse_value(name: &str, label: &str, raw: &str) -> Option<Value> {
183 let k = unit_scale(label, raw);
184 let cut = raw
186 .char_indices()
187 .find(|&(_, c)| matches!(c, '±' | '+' | '-' | '−' | '('))
188 .map_or(raw.len(), |(i, _)| i);
189 let nominal = &raw[..cut];
190 let nums = numbers(nominal);
191 if nums.is_empty() {
192 return None;
193 }
194 let lower = nominal.to_ascii_lowercase();
195 let is_dims = lower.contains(" x ") || lower.contains('×') || lower.contains("x");
196 let several = nums.len() > 1;
197 if several && !(name == "diameter" && is_dims && nums.len() == 2) {
198 return None;
199 }
200 if name == "diameter" && nums.len() == 2 {
201 let (a, b) = (nums[0].1 * k, nums[1].1 * k);
202 if (a - b).abs() < 1e-9 {
203 return Some(json!(round6(a)));
204 }
205 return Some(json!([round6(a), round6(b)]));
206 }
207 let x = nums[0].1 * k;
208 (x > 0.0 && x.is_finite()).then(|| json!(round6(x)))
209}
210
211fn round6(x: f64) -> f64 {
212 (x * 1e6).round() / 1e6
213}
214
215pub fn read_page(text: &str) -> PageRead {
218 let text = if text.len() > MAX_TEXT {
219 let mut e = MAX_TEXT;
220 while !text.is_char_boundary(e) {
221 e -= 1;
222 }
223 &text[..e]
224 } else {
225 text
226 };
227 let lines: Vec<&str> = text.lines().map(str::trim).collect();
228 let mut out = PageRead::default();
229 let mut best: [Option<(u8, Value)>; 5] = Default::default();
230 for (i, line) in lines.iter().enumerate() {
231 let (label, rest) = match line.find(':') {
233 Some(c) => (&line[..c], line[c + 1..].trim()),
234 None => match line.find('\t') {
235 Some(c) => (&line[..c], line[c + 1..].trim()),
236 None => (*line, ""),
237 },
238 };
239 let Some((name, prio)) = label_kind(label) else {
240 continue;
241 };
242 let raw = if rest.is_empty() {
244 match lines[i + 1..].iter().find(|x| !x.is_empty()) {
245 Some(n) if label_kind(n.split(':').next().unwrap_or("")).is_none() => *n,
246 _ => continue,
247 }
248 } else {
249 rest
250 };
251 if raw.len() > 80 || numbers(raw).is_empty() {
252 continue;
253 }
254 let value = if raw.contains('%') {
256 None
257 } else {
258 parse_value(name, label, raw)
259 };
260 let slot = match name {
261 "thickness" => 0,
262 "diameter" => 1,
263 "mount_thickness" => 2,
264 "mount_diameter" => 3,
265 _ => 4,
266 };
267 if let Some(v) = &value {
268 if best[slot].as_ref().is_none_or(|(p, _)| prio < *p) {
269 best[slot] = Some((prio, v.clone()));
270 }
271 }
272 out.found.push(Reading {
273 name,
274 label: label.trim().to_string(),
275 raw: raw.to_string(),
276 value,
277 });
278 }
279 out.thickness = best[0].take().and_then(|(_, v)| v.as_f64());
280 out.diameter = best[1].take().map(|(_, v)| v);
281 out.mount_thickness = best[2].take().and_then(|(_, v)| v.as_f64());
282 out.mount_diameter = best[3].take().and_then(|(_, v)| v.as_f64());
283 out.clear_aperture = best[4].take().and_then(|(_, v)| v.as_f64());
284 out
285}
286
287pub fn page_frame(
291 r: &PageRead,
292 thickness: Option<f64>,
293 glass: Option<f64>,
294) -> Option<lensbench_project::MechSpec> {
295 let len = r.mount_thickness.filter(|x| *x > 0.0)?;
296 let ca = r.clear_aperture.filter(|x| *x > 0.0)?;
297 let od = r
298 .mount_diameter
299 .or_else(|| r.diameter.as_ref().and_then(Value::as_f64))
300 .filter(|x| *x > ca)?;
301 let seat = thickness
302 .filter(|t| *t > 0.0 && *t <= len)
303 .map_or(0.0, |t| round6((len - t) / 2.0));
304 Some(lensbench_project::MechSpec {
305 bores: vec![lensbench_project::BoreSpec {
306 z0: 0.0,
307 z1: len,
308 diameter: ca,
309 }],
310 length: len,
311 outer_diameter: od,
312 holds: Some(lensbench_project::HoldSpec {
313 diameter: glass.filter(|g| *g >= ca && *g <= od).unwrap_or(ca),
314 seat_z: seat,
315 max_diameter: 0.0,
316 }),
317 ..Default::default()
318 })
319}
320
321#[derive(Clone, Copy, Debug, Default, PartialEq)]
323pub struct SpecValues {
324 pub thickness: Option<f64>,
325 pub diameter: Option<f64>,
326 pub mount_thickness: Option<f64>,
327 pub mount_diameter: Option<f64>,
328 pub clear_aperture: Option<f64>,
329}
330
331impl SpecValues {
332 pub fn of(specs: &serde_json::Map<String, Value>, page: Option<&PageRead>) -> Self {
334 let get = |k: &str| {
335 page.and_then(|p| p.get(k))
336 .or_else(|| specs.get(k).cloned())
337 .and_then(|v| v.as_f64())
338 .filter(|x| *x > 0.0 && x.is_finite())
339 };
340 SpecValues {
341 thickness: get("thickness"),
342 diameter: get("diameter"),
343 mount_thickness: get("mount_thickness"),
344 mount_diameter: get("mount_diameter"),
345 clear_aperture: get("clear_aperture"),
346 }
347 }
348
349 pub fn from_value(v: &Value) -> Self {
351 let m = v.as_object().cloned().unwrap_or_default();
352 Self::of(&m, None)
353 }
354
355 pub fn to_value(&self) -> Value {
356 let mut m = serde_json::Map::new();
357 for (k, v) in [
358 ("thickness", self.thickness),
359 ("diameter", self.diameter),
360 ("mount_thickness", self.mount_thickness),
361 ("mount_diameter", self.mount_diameter),
362 ("clear_aperture", self.clear_aperture),
363 ] {
364 if let Some(v) = v {
365 m.insert(k.into(), json!(v));
366 }
367 }
368 Value::Object(m)
369 }
370
371 fn frame_valued(&self, frame: Option<&lensbench_project::MechSpec>) -> (bool, bool) {
374 let Some(f) = frame else {
375 return (false, false);
376 };
377 let near = |a: Option<f64>, b: f64| a.is_some_and(|a| (a - b).abs() <= SPEC_TOL);
378 (
379 self.mount_thickness.is_none() && near(self.thickness, f.length),
380 self.mount_diameter.is_none() && near(self.diameter, f.outer_diameter),
381 )
382 }
383}
384
385pub const SPEC_TOL: f64 = 0.05;
387
388#[derive(Clone, Copy, Debug, PartialEq)]
390pub struct SpecCmp {
391 pub key: &'static str,
393 pub step: f64,
394 pub spec: f64,
395 pub spec_key: &'static str,
397}
398
399impl SpecCmp {
400 pub fn ok(&self) -> bool {
403 if self.key == "clear_aperture" {
404 self.spec <= self.step + SPEC_TOL
405 } else {
406 (self.step - self.spec).abs() <= SPEC_TOL
407 }
408 }
409
410 pub fn label(&self) -> &'static str {
412 match self.key {
413 "thickness" => "glass thickness",
414 "diameter" => "glass diameter",
415 "mount_thickness" => "mount thickness",
416 "mount_diameter" => "mount outer diameter",
417 _ => "clear aperture",
418 }
419 }
420
421 pub fn note(&self) -> String {
423 format!(
424 "{what}: STEP {} mm, spec table {} mm (difference {} mm)",
425 round6(self.step),
426 round6(self.spec),
427 round6(self.step - self.spec),
428 what = self.label(),
429 )
430 }
431}
432
433pub fn spec_check(
437 thickness: Option<f64>,
438 diameter: Option<f64>,
439 frame: Option<&lensbench_project::MechSpec>,
440 merged: bool,
441 s: &SpecValues,
442) -> Vec<SpecCmp> {
443 let (ft, fd) = s.frame_valued(frame);
444 let mut out = Vec::new();
445 let mut push = |key, step: Option<f64>, spec: Option<f64>, spec_key| {
446 if let (Some(step), Some(spec)) = (step, spec) {
447 out.push(SpecCmp {
448 key,
449 step,
450 spec,
451 spec_key,
452 });
453 }
454 };
455 if !ft {
456 push("thickness", thickness, s.thickness, "thickness");
457 }
458 if !fd && !merged {
459 push("diameter", diameter, s.diameter, "diameter");
460 }
461 if let Some(f) = frame {
462 let (mt, mtk) = if ft {
463 (s.thickness, "thickness")
464 } else {
465 (s.mount_thickness, "mount_thickness")
466 };
467 push("mount_thickness", Some(f.length), mt, mtk);
468 let (md, mdk) = if fd {
469 (s.diameter, "diameter")
470 } else {
471 (s.mount_diameter, "mount_diameter")
472 };
473 push("mount_diameter", Some(f.outer_diameter), md, mdk);
474 let clear = f
475 .bores
476 .iter()
477 .map(|b| b.diameter)
478 .fold(f64::INFINITY, f64::min);
479 push(
480 "clear_aperture",
481 clear.is_finite().then_some(clear),
482 s.clear_aperture,
483 "clear_aperture",
484 );
485 }
486 out
487}
488
489pub fn spec_glass_diameter(
492 visible: f64,
493 frame: &lensbench_project::MechSpec,
494 s: &SpecValues,
495) -> Option<f64> {
496 let (_, fd) = s.frame_valued(Some(frame));
497 s.diameter
498 .filter(|_| !fd)
499 .filter(|d| *d >= visible - SPEC_TOL && *d < frame.outer_diameter)
500}
501
502pub fn cad_check(mech: &lensbench_project::MechSpec, s: &StepSize) -> Vec<String> {
505 let mut v = Vec::new();
506 let Some(f) = s.frame.as_ref().filter(|_| s.mech) else {
507 return vec!["the mechanical dimensions can't be measured from the STEP (it has glass, no bore, or the like)".into()];
508 };
509 for (label, cat, step) in [
510 ("length", mech.length, f.length),
511 ("outer diameter", mech.outer_diameter, f.outer_diameter),
512 ] {
513 if cat > 0.0 && (cat - step).abs() > SPEC_TOL {
514 v.push(format!(
515 "{what}: catalog {} mm, STEP {} mm (difference {} mm)",
516 cat,
517 step,
518 round6(step - cat),
519 what = label,
520 ));
521 }
522 }
523 if mech.outline != f.outline {
524 v.push(
525 match (mech.outline.is_round(), f.outline.is_round()) {
526 (true, true) => "outline: catalog round, STEP round",
527 (true, false) => "outline: catalog round, STEP square",
528 (false, true) => "outline: catalog square, STEP round",
529 (false, false) => "outline: catalog square, STEP square",
530 }
531 .to_string(),
532 );
533 }
534 v
535}
536
537pub fn material_glass(material: &str) -> (&'static str, &'static str, bool) {
539 let m = material.to_ascii_lowercase();
540 let has = |k: &str| m.contains(k);
541 if has("fused silica") || has("7980") || has("fused quartz") || has("uvfs") {
542 ("F_SILICA", "MISC", false)
543 } else if has("n-bk7") || m.trim() == "bk7" || has("bk7") {
544 ("N-BK7", "SCHOTT", false)
545 } else if has("b270") || has("b 270") {
546 ("B270", "SCHOTT", false)
547 } else if has("caf2") || has("calcium fluoride") {
548 ("CAF2", "MISC", false)
549 } else if has("sapphire") {
550 ("SAPPHIRE", "INFRARED", false)
551 } else if has("baf2") || has("barium fluoride") {
552 ("BAF2", "INFRARED", false)
553 } else if has("germanium") {
554 ("GERMANIUM", "INFRARED", false)
555 } else if has("silicon") {
556 ("SILICON", "INFRARED", false)
557 } else if has("mgf2") || has("magnesium fluoride") {
558 ("MGF2", "INFRARED", false)
559 } else if has("znse") || has("zinc selenide") {
560 ("ZNSE", "INFRARED", false)
561 } else {
562 ("N-BK7", "SCHOTT", true)
563 }
564}
565
566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
568pub enum FillFrom {
569 Page,
571 Step,
573 Manual,
575}
576
577impl FillFrom {
578 pub fn parse(s: &str) -> FillFrom {
579 match s {
580 "page" => FillFrom::Page,
581 "step" => FillFrom::Step,
582 _ => FillFrom::Manual,
583 }
584 }
585 fn text(self) -> &'static str {
586 match self {
587 FillFrom::Page => "the spec table of the product page",
588 FillFrom::Step => "the STEP of the product page",
589 FillFrom::Manual => "the user input",
590 }
591 }
592}
593
594fn semi_of(d: &Value) -> Option<f64> {
596 let x = match d {
597 Value::Number(n) => n.as_f64()?,
598 Value::Array(a) => a.iter().filter_map(Value::as_f64).fold(0.0, f64::max),
599 _ => return None,
600 };
601 (x > 0.0 && x.is_finite()).then_some(x / 2.0)
602}
603
604pub fn complete(
611 item: &UserItem,
612 thickness: Option<f64>,
613 diameter: Option<Value>,
614 frame: Option<lensbench_project::MechSpec>,
615 from: FillFrom,
616 checked: &str,
617) -> lensbench_core::Result<UserItem> {
618 use lensbench_project::catalog_spec::ItemKind;
619 let mut it = item.clone();
620 for m in item.missing() {
621 let ok = match m.as_str() {
622 "thickness" => thickness.is_some_and(|t| t > 0.0 && t.is_finite()),
623 "diameter" => diameter.as_ref().and_then(semi_of).is_some(),
624 other => return Err(format!("value that can't be filled in: {other}").into()),
625 };
626 if !ok {
627 return Err(format!("a value for {m} is needed").into());
628 }
629 }
630 if let Some(t) = thickness.filter(|t| *t > 0.0 && t.is_finite()) {
631 it.specs.insert("thickness".into(), json!(t));
632 }
633 if let Some(d) = diameter.filter(|d| semi_of(d).is_some()) {
634 it.specs.insert("diameter".into(), d);
635 }
636 let t = it
637 .specs
638 .get("thickness")
639 .and_then(Value::as_f64)
640 .filter(|t| *t > 0.0);
641 let semi = it
642 .specs
643 .get("diameter")
644 .and_then(semi_of)
645 .ok_or("no diameter (diameter)")?;
646 let material = it
647 .specs
648 .get("material")
649 .and_then(Value::as_str)
650 .unwrap_or("")
651 .to_string();
652 let rect = match it.specs.get("diameter") {
654 Some(Value::Array(a)) if a.len() == 2 => match (a[0].as_f64(), a[1].as_f64()) {
655 (Some(w), Some(h)) if w > 0.0 && h > 0.0 => Some((w / 2.0, h / 2.0)),
656 _ => None,
657 },
658 _ => None,
659 };
660 let semi = rect.map_or(semi, |(hx, hy)| hx.hypot(hy));
661 let ap = rect.map(|(hx, hy)| json!({ "type": "rect", "hx": hx, "hy": hy }));
662 let surf = |mut v: Value| {
663 if let Some(a) = &ap {
664 v["aperture"] = a.clone();
665 }
666 v
667 };
668 let block = if it.kind == Some(ItemKind::Mirror) {
669 surf(json!({ "type": "mirror", "semi": semi }))
670 } else {
671 let t = t.ok_or("no thickness (thickness)")?;
672 let (glass, cat, sub) = material_glass(&material);
673 if sub {
674 it.notes.push(if material.is_empty() {
675 "no substrate glass is given, so blocks use N-BK7 instead".to_string()
676 } else {
677 format!(
678 "the glass of substrate \"{material}\" is unknown, so blocks use N-BK7 instead"
679 )
680 });
681 }
682 if !it.glass_catalogs.iter().any(|c| c == cat) {
683 it.glass_catalogs.push(cat.to_string());
684 }
685 json!({
686 "type": "lens",
687 "source": { "surfaces": [
688 surf(json!({ "t": t, "glass": glass, "semi": semi })),
689 surf(json!({ "semi": semi })),
690 ] },
691 })
692 };
693 let blocks = vec![serde_json::from_value(block).map_err(|e| format!("blocks: {e}"))?];
694 let mut frame_spec = None;
695 if let Some(f) = frame {
696 f.validate().map_err(|e| format!("mount: {e}"))?;
697 if f.bores.is_empty() {
698 return Err("mount: no bores (bores)".into());
699 }
700 let clear = f
701 .bores
702 .iter()
703 .map(|b| b.diameter)
704 .fold(f64::INFINITY, f64::min);
705 it.specs
706 .entry("clear_aperture".to_string())
707 .or_insert_with(|| json!(round6(clear)));
708 if let (Some(h), Some(t)) = (f.holds, t) {
709 let len = if f.length > 0.0 {
710 f.length
711 } else {
712 f.bores.iter().map(|b| b.z1).fold(0.0, f64::max)
713 };
714 if h.seat_z < 0.0 || h.seat_z + t > len + 1e-6 {
715 it.notes.push(format!(
716 "the glass ({} to {} mm) sticks out of the mount length {len} mm",
717 h.seat_z,
718 h.seat_z + t
719 ));
720 }
721 }
722 if from == FillFrom::Page {
723 it.notes
724 .push("the seat in the mount isn't in the spec table, so the glass is placed at the middle of the mount".into());
725 }
726 it.notes.push(format!(
727 "split the mount from {what}: length {} mm, outer diameter {} mm, smallest inner diameter {} mm",
728 f.length,
729 f.outer_diameter,
730 round6(clear),
731 what = from.text(),
732 ));
733 frame_spec = Some(f);
734 }
735 let thick = item.missing().iter().any(|m| m == "thickness");
736 let dia = item.missing().iter().any(|m| m != "thickness");
737 let what = match (thick, dia) {
738 (true, true) => "the thickness and diameter",
739 (true, false) => "the thickness",
740 _ => "the diameter",
741 };
742 it.notes.push(format!(
743 "filled {what} from {e} ({checked})",
744 e = from.text()
745 ));
746 if from != FillFrom::Manual && !it.url.is_empty() {
747 it.source = it.url.clone();
748 }
749 if !checked.is_empty() {
750 it.checked = checked.to_string();
751 }
752 if it.description.is_empty() {
753 let d = match it.specs.get("diameter") {
754 Some(Value::Array(a)) => a
755 .iter()
756 .map(|x| x.to_string())
757 .collect::<Vec<_>>()
758 .join(" × "),
759 Some(x) => x.to_string(),
760 None => "—".into(),
761 };
762 it.description = format!(
763 "{}{}diameter {d} mm, thickness {} mm",
764 it.title,
765 if it.title.is_empty() { "" } else { ", " },
766 t.map_or("—".into(), |x| format!("{x}")),
767 );
768 }
769 it.body = lensbench_project::ItemBody::Optic {
770 blocks,
771 frame: frame_spec.map(|spec| lensbench_project::Frame {
772 spec,
773 reversed: false,
774 }),
775 };
776 Ok(it)
777}
778
779pub fn date_of_unix(secs: u64) -> String {
781 let z = (secs / 86400) as i64 + 719468;
783 let era = z.div_euclid(146097);
784 let doe = z - era * 146097;
785 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
786 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
787 let mp = (5 * doy + 2) / 153;
788 let d = doy - (153 * mp + 2) / 5 + 1;
789 let m = if mp < 10 { mp + 3 } else { mp - 9 };
790 let y = yoe + era * 400 + i64::from(m <= 2);
791 format!("{y:04}-{m:02}-{d:02}")
792}
793
794#[cfg(test)]
795mod tests {
796 use super::*;
797
798 #[test]
799 fn page_reads_thickness_and_diameter() {
800 let t = "Physical & Mechanical Properties\nDiameter (mm):\n25.00 +0.00/-0.10\nThickness (mm):\n3.00 ±0.10\nMounted Thickness (mm):\n5.00\nClear Aperture CA (mm):\n22.00\n";
802 let r = read_page(t);
803 assert_eq!(r.thickness, Some(3.0));
804 assert_eq!(r.diameter, Some(json!(25.0)));
805 let r = read_page("Thickness (inches):\t0.25\nDiameter (mm): 12.5");
807 assert_eq!(r.thickness, Some(6.35));
808 assert_eq!(r.diameter, Some(json!(12.5)));
809 assert_eq!(
811 read_page("Thickness: 3.0 including AR coating").thickness,
812 Some(3.0)
813 );
814 assert_eq!(read_page("Thickness: 0.25 in").thickness, Some(6.35));
815 assert_eq!(read_page("Thickness: 0.25in").thickness, Some(6.35));
816 let r = read_page("Dimensions (mm):\n25.0 x 35.0\nThickness (mm): 1.1");
818 assert_eq!(r.diameter, Some(json!([25.0, 35.0])));
819 assert_eq!(r.thickness, Some(1.1));
820 }
821
822 fn frame(len: f64, od: f64, bore: f64) -> lensbench_project::MechSpec {
823 lensbench_project::MechSpec {
824 bores: vec![lensbench_project::BoreSpec {
825 z0: 0.0,
826 z1: len,
827 diameter: bore,
828 }],
829 length: len,
830 outer_diameter: od,
831 holds: Some(lensbench_project::HoldSpec {
832 diameter: bore,
833 seat_z: 0.5,
834 max_diameter: 0.0,
835 }),
836 ..Default::default()
837 }
838 }
839
840 #[test]
842 fn spec_check_compares_glass_and_frame() {
843 let r = read_page("Diameter (mm):\n25.00\nSubstrate Thickness (mm):\n2.00\nMount Thickness (mm):\n3.50\nClear Aperture CA (mm):\n21.00\n");
844 let s = SpecValues::of(&serde_json::Map::new(), Some(&r));
845 let f = frame(3.5, 24.99, 21.209);
846 let c = spec_check(Some(2.0), Some(23.9), Some(&f), false, &s);
847 let keys: Vec<_> = c.iter().map(|c| (c.key, c.ok())).collect();
848 assert_eq!(
850 keys,
851 [
852 ("thickness", true),
853 ("mount_thickness", true),
854 ("mount_diameter", true),
855 ("clear_aperture", true),
856 ]
857 );
858 assert_eq!(c[2].spec_key, "diameter");
859 let big = SpecValues {
861 clear_aperture: Some(22.0),
862 ..s
863 };
864 let c = spec_check(Some(2.0), Some(23.9), Some(&f), false, &big);
865 assert!(!c[3].ok());
866 assert!(
867 c[3].note()
868 .contains("clear aperture: STEP 21.209 mm, spec table 22 mm"),
869 "{}",
870 c[3].note()
871 );
872 let mut m = serde_json::Map::new();
874 m.insert("thickness".into(), json!(1.5));
875 m.insert("clear_aperture".into(), json!(21.2));
876 let s2 = SpecValues::of(&m, None);
877 assert_eq!((s2.thickness, s2.clear_aperture), (Some(1.5), Some(21.2)));
878 let c = spec_check(Some(2.0), None, Some(&f), false, &s2);
879 assert_eq!(
880 c.iter()
881 .filter(|c| !c.ok())
882 .map(|c| c.key)
883 .collect::<Vec<_>>(),
884 ["thickness"]
885 );
886 assert_eq!(SpecValues::from_value(&s.to_value()), s);
887 }
888
889 #[test]
892 fn spec_check_merged_and_glass_diameter() {
893 let f = frame(6.3, 25.4, 21.0);
894 let s = SpecValues {
895 thickness: Some(6.3),
896 diameter: Some(25.4),
897 clear_aperture: Some(21.0),
898 ..Default::default()
899 };
900 let c = spec_check(Some(5.3), Some(21.0), Some(&f), true, &s);
901 assert_eq!(
902 c.iter()
903 .map(|c| (c.key, c.spec_key, c.ok()))
904 .collect::<Vec<_>>(),
905 [
906 ("mount_thickness", "thickness", true),
907 ("mount_diameter", "diameter", true),
908 ("clear_aperture", "clear_aperture", true),
909 ]
910 );
911 assert_eq!(spec_glass_diameter(21.0, &f, &s), None);
913 let s = SpecValues {
915 diameter: Some(22.0),
916 mount_diameter: Some(25.4),
917 ..s
918 };
919 assert_eq!(spec_glass_diameter(21.0, &f, &s), Some(22.0));
920 assert_eq!(
921 spec_glass_diameter(
922 21.0,
923 &f,
924 &SpecValues {
925 diameter: Some(26.0),
926 ..s
927 }
928 ),
929 None
930 );
931 let c = spec_check(Some(2.0), Some(25.0), None, false, &s);
933 assert_eq!(
934 c.iter().map(|c| c.key).collect::<Vec<_>>(),
935 ["thickness", "diameter"]
936 );
937 }
938
939 #[test]
941 fn page_frame_from_mount_fields() {
942 let t = "Diameter (mm):\n25.00\nSubstrate Thickness (mm):\n2.00\nMount Thickness (mm):\n3.50\nClear Aperture CA (mm):\n21.00\n";
943 let r = read_page(t);
944 assert_eq!(r.thickness, Some(2.0));
945 assert_eq!(
946 (r.mount_thickness, r.mount_diameter, r.clear_aperture),
947 (Some(3.5), None, Some(21.0))
948 );
949 let f = page_frame(&r, r.thickness, Some(23.9)).unwrap();
950 assert_eq!(f.length, 3.5);
951 assert_eq!(f.outer_diameter, 25.0);
952 assert_eq!(f.bores.len(), 1);
953 assert_eq!((f.bores[0].z1, f.bores[0].diameter), (3.5, 21.0));
954 let h = f.holds.unwrap();
955 assert_eq!((h.seat_z, h.diameter), (0.75, 23.9));
956 assert_eq!(read_page("Clear Aperture (%): 90%").clear_aperture, None);
958 assert!(page_frame(&read_page("Mount Thickness (mm): 3.5"), None, None).is_none());
959 let it = incomplete("filter", &["thickness"], json!({ "diameter": 25.0 }));
961 let c = complete(&it, Some(2.0), None, Some(f), FillFrom::Page, "").unwrap();
962 assert_eq!(c.frame().unwrap().spec.length, 3.5);
963 assert_eq!(c.specs["clear_aperture"], json!(21.0));
964 assert!(
965 c.notes.iter().any(|n| n.contains("middle of the mount")),
966 "{:?}",
967 c.notes
968 );
969 let c = complete(
971 &it,
972 Some(4.0),
973 None,
974 page_frame(&r, None, None),
975 FillFrom::Page,
976 "",
977 )
978 .unwrap();
979 assert!(
980 c.notes.iter().any(|n| n.contains("sticks out")),
981 "{:?}",
982 c.notes
983 );
984 }
985
986 #[test]
987 fn page_without_values_does_not_stop() {
988 let r = read_page("");
989 assert_eq!(r, PageRead::default());
990 let r = read_page("Just a moment...\nVerify you are human\nThickness\n");
991 assert!(r.thickness.is_none() && r.diameter.is_none());
992 let r = read_page("Substrate Thickness (mm):\n2.00 & 3.00\n");
994 assert!(r.thickness.is_none());
995 assert_eq!(r.found.len(), 1);
996 assert!(r.found[0].value.is_none());
997 let big = "lorem ipsum dolor\n".repeat(400_000) + "Thickness (mm): 2.0\n";
999 let r = read_page(&big);
1000 assert!(r.thickness.is_none() || r.thickness == Some(2.0));
1001 }
1002
1003 #[test]
1004 fn center_thickness_is_second_choice() {
1005 let r = read_page("Center Thickness CT (mm): 4.0\nThickness (mm): 3.0\n");
1006 assert_eq!(r.thickness, Some(3.0));
1007 let r = read_page("Center Thickness CT (mm): 4.0\n");
1008 assert_eq!(r.thickness, Some(4.0));
1009 }
1010
1011 fn incomplete(kind: &str, missing: &[&str], specs: Value) -> UserItem {
1012 serde_json::from_value(json!({
1013 "kind": kind, "url": "https://example.com/p/1", "title": "Filter 1",
1014 "missing": missing, "specs": specs,
1015 }))
1016 .unwrap()
1017 }
1018
1019 #[test]
1020 fn complete_builds_blocks() {
1021 let it = incomplete("filter", &["thickness"], json!({ "diameter": 25.0 }));
1022 assert!(it.is_incomplete());
1023 assert!(complete(&it, None, None, None, FillFrom::Page, "2026-11-10").is_err());
1024 let c = complete(&it, Some(3.0), None, None, FillFrom::Page, "2026-11-10").unwrap();
1025 assert!(!c.is_incomplete() && c.missing().is_empty());
1026 assert_eq!(c.blocks().len(), 1);
1027 assert_eq!(c.specs["thickness"], json!(3.0));
1028 assert_eq!(c.glass_catalogs, vec!["SCHOTT"]);
1029 assert_eq!(c.source, "https://example.com/p/1");
1030 assert_eq!(c.checked, "2026-11-10");
1031 assert!(c.notes.iter().any(|n| n.contains("use N-BK7 instead")));
1032 let b = serde_json::to_value(&c.blocks()[0]).unwrap();
1033 assert_eq!(b["type"], "lens");
1034 let m = incomplete(
1036 "mirror",
1037 &["diameter"],
1038 json!({ "material": "Fused Silica" }),
1039 );
1040 let c = complete(
1041 &m,
1042 None,
1043 Some(json!(25.4)),
1044 None,
1045 FillFrom::Step,
1046 "2026-11-10",
1047 )
1048 .unwrap();
1049 let b = serde_json::to_value(&c.blocks()[0]).unwrap();
1050 assert_eq!(b["type"], "mirror");
1051 assert_eq!(b["semi"], json!(12.7));
1052 let w = incomplete(
1054 "polarizer",
1055 &["diameter"],
1056 json!({ "thickness": 2, "material": "Fused Silica (Corning 7980)" }),
1057 );
1058 let c = complete(
1059 &w,
1060 None,
1061 Some(json!([10.0, 20.0])),
1062 None,
1063 FillFrom::Manual,
1064 "",
1065 )
1066 .unwrap();
1067 assert_eq!(c.glass_catalogs, vec!["MISC"]);
1068 let b = serde_json::to_value(&c.blocks()[0]).unwrap();
1070 for q in b["source"]["surfaces"].as_array().unwrap() {
1071 assert_eq!(q["aperture"]["type"], "rect", "{q}");
1072 assert_eq!(q["aperture"]["hx"], json!(5.0));
1073 assert_eq!(q["aperture"]["hy"], json!(10.0));
1074 assert!((q["semi"].as_f64().unwrap() - 125f64.sqrt()).abs() < 1e-12);
1075 }
1076 let c = complete(
1077 &m,
1078 None,
1079 Some(json!([10.0, 20.0])),
1080 None,
1081 FillFrom::Manual,
1082 "",
1083 )
1084 .unwrap();
1085 let b = serde_json::to_value(&c.blocks()[0]).unwrap();
1086 assert_eq!(b["aperture"]["hx"], json!(5.0));
1087 assert_eq!(b["aperture"]["hy"], json!(10.0));
1088 assert!(c.notes.iter().all(|n| !n.contains("N-BK7 instead")));
1089 }
1090
1091 #[test]
1092 fn dates() {
1093 assert_eq!(date_of_unix(0), "1970-01-01");
1094 assert_eq!(date_of_unix(1_794_268_800), "2026-11-10");
1095 }
1096}