Skip to main content

lensbench_project/
open.rs

1//! 系のファイル(.zmx・プロジェクトファイル・系ファイル)を拡張子で見分けて読む。CLI・serve・Python
2//! の共通の入口。誤りは core の [`Error`] で、種類(読込・不正・未対応)が付く
3
4use std::path::{Path, PathBuf};
5
6use lensbench_core::catalog::LensCatalog;
7use lensbench_core::error::code;
8use lensbench_core::{Error, System};
9use lensbench_formats::zmx;
10
11/// 読み方の引数の組み合わせ・値の誤り(符号 [`code::BAD_ARGUMENT`])
12fn bad_arg(m: String) -> Error {
13    Error::Invalid(m).with_code(code::BAD_ARGUMENT)
14}
15
16/// 系のファイルの種類(拡張子と中身で決める)
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum FileKind {
19    /// OpticStudio の .zmx(.json 以外はすべてこれとして読む)
20    Zmx,
21    /// プロジェクトファイル(ブロックで組む .json)
22    Project,
23    /// 系ファイル(lensbench 独自の .json、`"format": "lensbench-system"`)
24    SystemFile,
25}
26
27impl FileKind {
28    /// パスの種類。.json は中身を読んで系ファイルかを見る(読めなければプロジェクトとする)
29    pub fn of(path: &Path) -> FileKind {
30        if !is_json(path) {
31            FileKind::Zmx
32        } else if crate::sysfile::is_system_file(path) {
33            FileKind::SystemFile
34        } else {
35            FileKind::Project
36        }
37    }
38}
39
40/// 拡張子が .json か(大文字小文字を区別しない)
41pub fn is_json(path: &Path) -> bool {
42    path.extension()
43        .is_some_and(|x| x.eq_ignore_ascii_case("json"))
44}
45
46/// 読み方
47#[derive(Clone, Default)]
48pub struct OpenSpec<'a> {
49    /// ガラスカタログを探すフォルダ
50    pub glass_dirs: &'a [PathBuf],
51    /// プロジェクトファイルのカタログレンズを探すレンズカタログ
52    pub lens_catalogs: &'a [PathBuf],
53    /// .zmx の多重構成の番号(1 始まり。0 は誤り)
54    pub cfg: usize,
55    /// プロジェクトファイルの状態の名前
56    pub state: Option<&'a str>,
57    /// プロジェクトファイルのビームスプリッターの経路
58    pub split_path: Option<&'a str>,
59    /// .zmx の波長を置き換える [µm]
60    pub wavelengths: Option<Vec<f64>>,
61    /// 誤りの文に書く引数の名前
62    pub names: ArgNames,
63    /// プロジェクトの機構部品の詳しい形の STEP を引く口([`crate::Env::step_files`]。None は簡易外形)
64    pub step_files: Option<crate::StepLookup<'a>>,
65}
66
67impl OpenSpec<'_> {
68    /// 展開で読んだものを使い回してよい範囲([`crate::SourceCache::scope`])
69    fn cache_scope(&self) -> String {
70        format!("{:?}|{:?}", self.glass_dirs, self.lens_catalogs)
71    }
72}
73
74impl std::fmt::Debug for OpenSpec<'_> {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        f.debug_struct("OpenSpec")
77            .field("glass_dirs", &self.glass_dirs)
78            .field("lens_catalogs", &self.lens_catalogs)
79            .field("cfg", &self.cfg)
80            .field("state", &self.state)
81            .field("split_path", &self.split_path)
82            .field("wavelengths", &self.wavelengths)
83            .field("names", &self.names)
84            .field("step_files", &self.step_files.is_some())
85            .finish()
86    }
87}
88
89/// 誤りの文に書く引数(構成・状態・経路)の名前。呼ぶ側の書き方に合わせる
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct ArgNames {
92    pub cfg: &'static str,
93    pub state: &'static str,
94    pub split_path: &'static str,
95}
96
97impl ArgNames {
98    /// CLI の旗
99    pub const CLI: ArgNames = ArgNames {
100        cfg: "--cfg",
101        state: "--state",
102        split_path: "--beam-path",
103    };
104    /// serve の load の引数
105    pub const SERVE: ArgNames = ArgNames {
106        cfg: "cfg",
107        state: "state",
108        split_path: "beam_path",
109    };
110    /// Python の System.load の引数
111    pub const PYTHON: ArgNames = ArgNames {
112        cfg: "cfg",
113        state: "state",
114        split_path: "beam_path",
115    };
116}
117
118/// 既定は CLI の旗
119impl Default for ArgNames {
120    fn default() -> Self {
121        ArgNames::CLI
122    }
123}
124
125/// 読んだ系
126#[derive(Clone, Debug)]
127pub struct Opened {
128    pub system: System,
129    /// 注意(呼ぶ側が表示する)
130    pub warnings: Vec<String>,
131    /// 系ファイルに書いてあった膜の実測表・モデルのパス
132    pub coatings: Vec<PathBuf>,
133    /// プロジェクトの id のあるブロック・群ごとの系の面の範囲([`crate::block_spans`]。プロジェクトでなければ空)
134    pub blocks: Vec<crate::BlockSpans>,
135    /// プロジェクトの展開した系の面ごとの名前([`crate::SurfOrigin::face`]。別の状態・経路へ編集を当て直す
136    /// [`crate::retarget::Retarget`])。プロジェクトでなければ空
137    pub faces: Vec<Option<crate::FaceId>>,
138}
139
140/// 系ファイル(lensbench 独自の JSON)・プロジェクトファイル(.json)・.zmx を読む([`Source::read`] と [`Source::open`])。
141/// ファイルが無い・読めないときは [`Error::Io`]、引数の組み合わせや中身の誤りは [`Error::Invalid`]
142pub fn open(path: &Path, o: &OpenSpec) -> Result<Opened, Error> {
143    if o.cfg == 0 {
144        return Err(bad_arg(format!("{} must be 1 or more", o.names.cfg)));
145    }
146    Source::read(path)?.open(o)
147}
148
149/// [`open`] に、プロジェクトの機構部品の詳しい形の STEP を引く口([`crate::Env::step_files`])を足したもの
150pub fn open_with(
151    path: &Path,
152    o: &OpenSpec,
153    step_files: Option<crate::StepLookup>,
154) -> Result<Opened, Error> {
155    open(
156        path,
157        &OpenSpec {
158            step_files,
159            ..o.clone()
160        },
161    )
162}
163
164/// 1 回だけ読んだ系のファイル。プロジェクトは JSON を 1 回読んで解釈し、状態の名前・ビームスプリッターの経路・
165/// 状態ごとの系をそこから引く(CLI・serve・Python の共通の入口)。系ファイル・.zmx は種類とパスだけ持ち、[`Source::open`] で読む
166#[derive(Clone, Debug)]
167pub enum Source {
168    /// .zmx(中身は読んだときのもの。別の構成もここから作り、ファイルは読み直さない)
169    Zmx { path: PathBuf, text: String },
170    /// 系ファイル(中身は読んだときのもの)
171    SystemFile { path: PathBuf, text: String },
172    Project {
173        path: PathBuf,
174        /// ファイルの中身(状態は当てない)
175        text: String,
176        project: Box<crate::Project>,
177        /// 状態・経路ごとの展開で、ブロックが読むファイル・カタログの玉を使い回す
178        cache: std::sync::Arc<crate::SourceCache>,
179    },
180}
181
182impl Source {
183    /// パスの種類を決め、プロジェクトなら読んで解釈する。無い・フォルダ・読めないは [`Error::Io`]、
184    /// プロジェクトの中身の誤りは [`Error::Invalid`]
185    pub fn read(path: &Path) -> Result<Source, Error> {
186        if lensbench_core::vfs::is_dir(path) {
187            return Err(
188                Error::Io(format!("{}: a folder (give a system file)", path.display()))
189                    .with_code(code::IS_FOLDER),
190            );
191        }
192        if !lensbench_core::vfs::is_file(path) {
193            return Err(Error::Io(format!("{}: no such file", path.display()))
194                .with_code(code::FILE_NOT_FOUND));
195        }
196        let path_buf = path.to_path_buf();
197        if !is_json(path) {
198            let text = lensbench_core::glass::read_text(path)
199                .map_err(|e| Error::Io(format!("{}: {e}", path.display())))?;
200            return Ok(Source::Zmx {
201                path: path_buf,
202                text,
203            });
204        }
205        let txt = lensbench_core::vfs::read_to_string(path)
206            .map_err(|e| Error::Io(format!("{}: {e}", path.display())))?;
207        if crate::sysfile::is_system_json(&txt) {
208            return Ok(Source::SystemFile {
209                path: path_buf,
210                text: txt,
211            });
212        }
213        let project = crate::Project::from_json(&txt).map_err(|e| e.at(path.display()))?;
214        Ok(Source::Project {
215            path: path_buf,
216            text: txt,
217            project: Box::new(project),
218            cache: Default::default(),
219        })
220    }
221
222    /// ファイルの種類
223    pub fn kind(&self) -> FileKind {
224        match self {
225            Source::Zmx { .. } => FileKind::Zmx,
226            Source::SystemFile { .. } => FileKind::SystemFile,
227            Source::Project { .. } => FileKind::Project,
228        }
229    }
230
231    /// ファイルのパス
232    pub fn path(&self) -> &Path {
233        match self {
234            Source::Zmx { path: p, .. }
235            | Source::SystemFile { path: p, .. }
236            | Source::Project { path: p, .. } => p,
237        }
238    }
239
240    /// .zmx の構成 cfgs(1 始まり、空なら全部)の系(読んだときの中身から。.zmx でなければ誤り)
241    pub fn zmx_configs(
242        &self,
243        opt: &zmx::LoadOptions,
244        cfgs: &[usize],
245    ) -> Result<Vec<System>, Error> {
246        match self {
247            Source::Zmx { path, text } => zmx::load_configs_text(text, path, opt, cfgs),
248            _ => Err(bad_arg("configurations are only for .zmx".into())),
249        }
250    }
251
252    /// .zmx の構成の数(.zmx でなければ 1)
253    pub fn configurations(&self) -> Result<usize, Error> {
254        match self {
255            Source::Zmx { text, .. } => Ok(zmx::parse_text(text)?.configurations()),
256            _ => Ok(1),
257        }
258    }
259
260    /// 読んだプロジェクト(プロジェクトファイルでなければ None)
261    pub fn project(&self) -> Option<&crate::Project> {
262        match self {
263            Source::Project { project, .. } => Some(project),
264            _ => None,
265        }
266    }
267
268    /// プロジェクトファイルの中身(状態は当てない。プロジェクトファイルでなければ None)
269    pub fn project_text(&self) -> Option<&str> {
270        match self {
271            Source::Project { text, .. } => Some(text),
272            _ => None,
273        }
274    }
275
276    /// プロジェクトの状態の名前(.zmx・系ファイルなら空)
277    pub fn states(&self) -> Vec<String> {
278        self.project()
279            .map(|p| p.state_names().iter().map(|s| s.to_string()).collect())
280            .unwrap_or_default()
281    }
282
283    /// プロジェクトの光束の名前(.zmx・系ファイル・光束なしなら空)
284    pub fn beams(&self) -> Vec<String> {
285        self.project()
286            .map(|p| p.beam_names().iter().map(|s| s.to_string()).collect())
287            .unwrap_or_default()
288    }
289
290    /// プロジェクトの状態 state(None は既定の状態)
291    fn project_in(&self, state: Option<&str>) -> Result<Option<crate::Project>, Error> {
292        let Some(p) = self.project() else {
293            return Ok(None);
294        };
295        Ok(Some(match state {
296            Some(n) => p.with_state(n)?,
297            None => p.clone(),
298        }))
299    }
300
301    /// プロジェクトを展開する場(相対パスはファイルのフォルダから)
302    fn env<'c>(&self, o: &OpenSpec<'c>, cat: Option<crate::CatalogLookup<'c>>) -> crate::Env<'c> {
303        crate::Env {
304            base: self
305                .path()
306                .parent()
307                .map(|p| p.to_path_buf())
308                .unwrap_or_default(),
309            glass_dirs: o.glass_dirs.to_vec(),
310            catalog: cat,
311            step_files: o.step_files,
312        }
313    }
314
315    /// 状態 o.state のビームスプリッターの経路の一覧(.zmx・系ファイル・BS なしなら空)
316    pub fn paths(&self, o: &OpenSpec) -> Result<Vec<String>, Error> {
317        let Some(p) = self.project_in(o.state)? else {
318            return Ok(Vec::new());
319        };
320        let cat = LensCatalog::load_registered(o.lens_catalogs)?;
321        let look = |v: &str, q: &str| cat.zmx(v, q);
322        let cache = match self {
323            Source::Project { cache, .. } => cache.clone(),
324            _ => Default::default(),
325        };
326        cache.scope(&o.cache_scope());
327        crate::paths_cached(&p, &self.env(o, Some(&look)), &cache)
328    }
329
330    /// 系を読む([`open`] と同じ誤り)
331    pub fn open(&self, o: &OpenSpec) -> Result<Opened, Error> {
332        let ArgNames {
333            cfg,
334            state,
335            split_path: split,
336        } = o.names;
337        if o.cfg == 0 {
338            return Err(bad_arg(format!("{cfg} must be 1 or more")));
339        }
340        match self {
341            Source::SystemFile { path, text } => {
342                if o.cfg != 1 || o.state.is_some() || o.split_path.is_some() {
343                    return Err(bad_arg(format!(
344                        "{cfg}, {state} and {split} can't be used with a system file"
345                    )));
346                }
347                if o.wavelengths.is_some() {
348                    return Err(bad_arg(
349                        "wavelengths is only for .zmx and project files".into(),
350                    ));
351                }
352                let (system, m, warnings) =
353                    crate::sysfile::load_text_with(path, text, o.glass_dirs)?;
354                Ok(Opened {
355                    system,
356                    warnings,
357                    coatings: m.coatings,
358                    blocks: Vec::new(),
359                    faces: Vec::new(),
360                })
361            }
362            Source::Project {
363                path,
364                project,
365                cache,
366                ..
367            } => {
368                if o.cfg != 1 {
369                    return Err(bad_arg(format!(
370                        "choose the state with {state}, not {cfg}, in a project file"
371                    )));
372                }
373                let at = |e: Error| e.at(path.display());
374                let mut p = match o.state {
375                    Some(n) => project
376                        .with_state_and_path(n, o.split_path.is_some())
377                        .map_err(at)?,
378                    None => (**project).clone(),
379                };
380                // 追跡する波長を置き換える(重みは 1、主波長の番号はそのまま。.zmx と同じ)
381                if let Some(w) = &o.wavelengths {
382                    if p.primary == 0 || p.primary > w.len() {
383                        let (pw, nw) = (p.primary, w.len());
384                        return Err(at(Error::Invalid(format!(
385                            "primary wavelength {pw} (there are {nw} wavelengths)"
386                        ))));
387                    }
388                    p.wavelengths = w
389                        .iter()
390                        .map(|&um| crate::model::Wave { um, weight: 1.0 })
391                        .collect();
392                }
393                let cat = LensCatalog::load_registered(o.lens_catalogs)?;
394                let look = |v: &str, q: &str| cat.zmx(v, q);
395                cache.scope(&o.cache_scope());
396                let x = crate::expand(
397                    &p,
398                    &self.env(o, Some(&look)),
399                    &crate::ExpandOpts {
400                        path: o.split_path,
401                        cache: Some(cache),
402                        ..Default::default()
403                    },
404                )
405                .map_err(|e| at(e.into()))?;
406                let blocks = x.block_spans();
407                let faces = x.map.into_iter().map(|o| o.face).collect();
408                Ok(Opened {
409                    system: x.system,
410                    warnings: x.notes.into_iter().map(String::from).collect(),
411                    coatings: Vec::new(),
412                    blocks,
413                    faces,
414                })
415            }
416            Source::Zmx { path, text } => {
417                if o.state.is_some() {
418                    return Err(bad_arg(format!(
419                        "{state} is only for project files (.json) (.zmx uses {cfg})"
420                    )));
421                }
422                if o.split_path.is_some() {
423                    return Err(bad_arg(format!(
424                        "{split} is only for project files (.json)"
425                    )));
426                }
427                let opt = zmx::LoadOptions {
428                    cfg: o.cfg,
429                    catalog_dirs: o.glass_dirs.to_vec(),
430                    wavelengths: o.wavelengths.clone(),
431                    ..Default::default()
432                };
433                Ok(Opened {
434                    system: zmx::load_text_with(text, path, &opt)?,
435                    warnings: Vec::new(),
436                    coatings: Vec::new(),
437                    blocks: Vec::new(),
438                    faces: Vec::new(),
439                })
440            }
441        }
442    }
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448
449    #[test]
450    fn missing_file_is_io() {
451        let o = OpenSpec {
452            cfg: 1,
453            ..Default::default()
454        };
455        for f in ["nosuch.zmx", "nosuch.json", "nosuch.lbsys.json"] {
456            let e = open(Path::new(f), &o).unwrap_err();
457            assert_eq!(e.kind(), "io", "{f}: {e}");
458            assert_eq!(e.code(), code::FILE_NOT_FOUND, "{f}: {e}");
459        }
460    }
461
462    #[test]
463    fn bad_arguments_are_invalid() {
464        let o = OpenSpec {
465            cfg: 0,
466            ..Default::default()
467        };
468        let e = open(Path::new("x.zmx"), &o).unwrap_err();
469        assert_eq!((e.kind(), e.code()), ("invalid", code::BAD_ARGUMENT));
470    }
471
472    #[test]
473    fn file_kinds() {
474        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
475        let prj = root.join("examples/projects/P10_catalog_four.json");
476        assert_eq!(FileKind::of(&prj), FileKind::Project);
477        assert_eq!(
478            FileKind::of(&root.join("tests/refs/A0/system.zmx")),
479            FileKind::Zmx
480        );
481        let a0 = lensbench_formats::zmx::load_with(
482            &root.join("tests/refs/A0/system.zmx"),
483            &lensbench_formats::zmx::LoadOptions {
484                cfg: 1,
485                catalog_dirs: vec![root.join("tests/glass")],
486                ..Default::default()
487            },
488        )
489        .unwrap();
490        let s = crate::sysfile::to_string(&a0, &[]).unwrap();
491        let dir = std::env::temp_dir().join(format!("lb_open_kind_{}", std::process::id()));
492        std::fs::create_dir_all(&dir).unwrap();
493        let f = dir.join("sys.JSON");
494        std::fs::write(&f, s).unwrap();
495        assert_eq!(FileKind::of(&f), FileKind::SystemFile);
496        let _ = std::fs::remove_dir_all(&dir);
497    }
498
499    /// プロジェクトでも追跡する波長を置き換えて読める(重みは 1、主波長の番号はそのまま。番号が並びを越えれば誤り)
500    #[test]
501    fn project_with_replaced_wavelengths() {
502        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
503        let glass = [root.join("tests/glass")];
504        let src = Source::read(&root.join("examples/projects/P16_twyman_green.json")).unwrap();
505        let o = OpenSpec {
506            glass_dirs: &glass,
507            cfg: 1,
508            state: Some("reference arm"),
509            wavelengths: Some(vec![0.84, 0.83, 0.85]),
510            ..Default::default()
511        };
512        let s = src.open(&o).unwrap().system;
513        assert_eq!(s.wavelengths, vec![0.84, 0.83, 0.85]);
514        assert_eq!(s.weights, vec![1.0; 3]);
515        assert_eq!(s.primary, 0);
516        let plain = src
517            .open(&OpenSpec {
518                wavelengths: None,
519                ..o.clone()
520            })
521            .unwrap()
522            .system;
523        assert_eq!(s.surfaces.len(), plain.surfaces.len());
524        let e = src
525            .open(&OpenSpec {
526                wavelengths: Some(Vec::new()),
527                ..o
528            })
529            .unwrap_err();
530        assert!(e.to_string().contains("primary wavelength 1"), "{e}");
531    }
532
533    /// プロジェクトは 1 回読んで、状態・経路・状態ごとの系をそこから引く(ファイルから直に読んだものと同じ)
534    #[test]
535    fn source_reads_the_project_once() {
536        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
537        let glass = [root.join("tests/glass")];
538        for f in ["P16_twyman_green.json", "P6_states_focus_group.json"] {
539            let path = root.join("examples/projects").join(f);
540            let src = Source::read(&path).unwrap();
541            assert_eq!(src.kind(), FileKind::Project);
542            assert!(src.project_text().is_some());
543            let names = src.states();
544            assert_eq!(names, src.project().unwrap().state_names());
545            let mut states: Vec<Option<&str>> = vec![None];
546            states.extend(names.iter().map(|s| Some(s.as_str())));
547            for st in states {
548                let o = OpenSpec {
549                    glass_dirs: &glass,
550                    cfg: 1,
551                    state: st,
552                    ..Default::default()
553                };
554                let direct = open(&path, &o).unwrap().system;
555                let s = src.open(&o).unwrap().system;
556                assert_eq!(format!("{s:?}"), format!("{direct:?}"), "{f} {st:?}");
557                src.paths(&o).unwrap();
558            }
559        }
560    }
561
562    /// 誤りの符号は読む所を通っても残る(状態の名前・ガラス)
563    #[test]
564    fn codes_survive_open() {
565        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
566        let glass = [root.join("tests/glass")];
567        let p = root.join("examples/projects/P6_states_focus_group.json");
568        let o = OpenSpec {
569            glass_dirs: &glass,
570            cfg: 1,
571            state: Some("nosuch"),
572            ..Default::default()
573        };
574        let e = open(&p, &o).unwrap_err();
575        assert_eq!(
576            (e.kind(), e.code()),
577            ("invalid", code::STATE_NOT_FOUND),
578            "{e}"
579        );
580        // ガラスのフォルダが空で、同梱にも無いカタログ(SCHOTT・OHARA は同梱から取る)
581        let empty = std::env::temp_dir().join(format!("lb_open_code_{}", std::process::id()));
582        std::fs::create_dir_all(&empty).unwrap();
583        let src = std::fs::read_to_string(root.join("examples/projects/P5_triplet_blocks.json"))
584            .unwrap()
585            .replace("\"SCHOTT\"", "\"NOSUCHCAT\"")
586            .replace(
587                "../../tests/refs",
588                &root
589                    .join("tests/refs")
590                    .display()
591                    .to_string()
592                    .replace('\\', "/"),
593            );
594        let proj = empty.join("p.json");
595        std::fs::write(&proj, src).unwrap();
596        let dirs = [empty.clone()];
597        let o = OpenSpec {
598            glass_dirs: &dirs,
599            cfg: 1,
600            ..Default::default()
601        };
602        let e = open(&proj, &o).unwrap_err();
603        let _ = std::fs::remove_dir_all(&empty);
604        assert_eq!(e.code(), code::GLASS_NOT_FOUND, "{e}");
605        assert!(e.to_string().contains("--glass-dir"), "{e}");
606    }
607
608    #[test]
609    fn folder_is_io_with_its_own_message() {
610        let o = OpenSpec {
611            cfg: 1,
612            ..Default::default()
613        };
614        let e = open(Path::new("."), &o).unwrap_err();
615        assert_eq!((e.kind(), e.code()), ("io", code::IS_FOLDER));
616        assert!(e.message().unwrap_or_default().contains("a folder"), "{e}");
617    }
618}