Skip to main content

lensbench_core/
plugin.rs

1//! 検出器・解析のプラグインの約束。
2//!
3//! プラグインは [`Plugin`] を実装し、名前で [`Registry`] に登録する。呼ぶ側は名前と設定([`Config`]: 数・真偽・文字列・
4//! 数の並びの小さな辞書)から [`Instance`] を作り、名前つきの配列([`Arrays`])を渡して名前つきの配列を受け取る。
5//!
6//! 約束:
7//! - [`Plugin::prepare`] で設定を確かめ、設定から決まる前処理(係数・作用素など)をここで済ませる。
8//! - [`Instance::run`] は 1 回の呼び出しの中では、原則として単一スレッドで計算し(系を追跡するものは
9//!   [`crate::with_threads`] の指定に従ってよい)、呼び出しの間で状態を持たない(同じ入力なら
10//!   同じビットを返す)。`&self` で呼ぶので、同じ `Instance` を複数のスレッドから同時に呼んでよい
11//!   ([`run_many`])。入力の形によるキャッシュ(最小二乗の作用素など)は、結果を変えない限り中で持ってよい。
12//! - 入力の名前・形・型が合わなければ [`crate::Error::Invalid`] を返す(panic しない)。
13//!
14//! 組み込みのプラグインはワークスペース内の別 crate に置き、その crate の `register(&mut Registry)` で登録する
15//! (例: `lensbench-analysis`)。Python からのコールバックも同じ [`Plugin`] として登録できる。
16
17use std::collections::BTreeMap;
18use std::sync::Arc;
19
20use crate::coating::{Coatings, C64};
21use crate::{invalid, Result, System};
22
23/// プラグインの種類
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
25pub enum Kind {
26    /// 検出器: 検出面の場・光線から画素の値を作る
27    Detector,
28    /// 解析: 結果の配列から値・配列を作る
29    Analysis,
30}
31
32impl Kind {
33    pub fn as_str(self) -> &'static str {
34        match self {
35            Kind::Detector => "detector",
36            Kind::Analysis => "analysis",
37        }
38    }
39
40    pub fn parse(s: &str) -> Result<Self> {
41        match s {
42            "detector" => Ok(Kind::Detector),
43            "analysis" => Ok(Kind::Analysis),
44            _ => invalid!("plugin kind must be detector or analysis ({s})"),
45        }
46    }
47}
48
49/// 設定の値(系ファイルの JSON では数・真偽・文字列・数の並びをそのまま書く)
50#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
51#[serde(untagged)]
52#[derive(schemars::JsonSchema)]
53pub enum Value {
54    Num(f64),
55    /// 真偽([`ConfigReader::flag`]。0・1 の数も受ける)
56    Bool(bool),
57    Str(String),
58    /// 数の並び(角度 4 個など)
59    Nums(Vec<f64>),
60}
61
62/// 設定: 名前 → 値
63pub type Config = BTreeMap<String, Value>;
64
65/// 設定を読む補助。知らない名前を残さないよう、読んだ名前を覚えて [`ConfigReader::finish`] で確かめる
66pub struct ConfigReader<'a> {
67    cfg: &'a Config,
68    used: Vec<&'a str>,
69}
70
71impl<'a> ConfigReader<'a> {
72    pub fn new(cfg: &'a Config) -> Self {
73        Self {
74            cfg,
75            used: Vec::new(),
76        }
77    }
78
79    fn get(&mut self, key: &str) -> Option<&'a Value> {
80        let (k, v) = self.cfg.get_key_value(key)?;
81        self.used.push(k);
82        Some(v)
83    }
84
85    /// 数(省けば `default`)
86    pub fn num(&mut self, key: &str, default: f64) -> Result<f64> {
87        match self.get(key) {
88            None => Ok(default),
89            Some(Value::Num(x)) => Ok(*x),
90            Some(Value::Nums(v)) if v.len() == 1 => Ok(v[0]),
91            Some(v) => invalid!("setting {key} must be a number ({v:?})"),
92        }
93    }
94
95    /// 数(省けば None)。NaN は「省略」の印にせず誤り(省くときは書かない)
96    pub fn opt_num(&mut self, key: &str) -> Result<Option<f64>> {
97        if !self.cfg.contains_key(key) {
98            return Ok(None);
99        }
100        let x = self.num(key, 0.0)?;
101        if x.is_nan() {
102            invalid!("setting {key} is NaN (leave it out to omit it)");
103        }
104        Ok(Some(x))
105    }
106
107    /// 文字列(省けば `default`)
108    pub fn str(&mut self, key: &str, default: &str) -> Result<String> {
109        match self.get(key) {
110            None => Ok(default.to_string()),
111            Some(Value::Str(s)) => Ok(s.clone()),
112            Some(v) => invalid!("setting {key} must be a string ({v:?})"),
113        }
114    }
115
116    /// 数の並び(省けば None)。数 1 つも長さ 1 の並びとして受ける
117    pub fn nums(&mut self, key: &str) -> Result<Option<Vec<f64>>> {
118        match self.get(key) {
119            None => Ok(None),
120            Some(Value::Num(x)) => Ok(Some(vec![*x])),
121            Some(Value::Nums(v)) => Ok(Some(v.clone())),
122            Some(v) => invalid!("setting {key} must be a list of numbers ({v:?})"),
123        }
124    }
125
126    /// 0 以上の整数(省けば `default`)
127    pub fn count(&mut self, key: &str, default: usize) -> Result<usize> {
128        Ok(self.opt_count(key)?.unwrap_or(default))
129    }
130
131    /// 0 以上の整数(省けば None。NaN を「省略」の印にしない)
132    pub fn opt_count(&mut self, key: &str) -> Result<Option<usize>> {
133        if !self.cfg.contains_key(key) {
134            return Ok(None);
135        }
136        let x = self.num(key, 0.0)?;
137        if !(x >= 0.0) || x.fract() != 0.0 || x > u32::MAX as f64 {
138            invalid!("setting {key} must be an integer 0 or more ({x})");
139        }
140        Ok(Some(x as usize))
141    }
142
143    /// 真偽(true・false か 0・1、省けば `default`)
144    pub fn flag(&mut self, key: &str, default: bool) -> Result<bool> {
145        if let Some(Value::Bool(b)) = self.cfg.get(key) {
146            self.get(key);
147            return Ok(*b);
148        }
149        match self.num(key, if default { 1.0 } else { 0.0 })? {
150            0.0 => Ok(false),
151            1.0 => Ok(true),
152            x => invalid!("setting {key} must be true or false (or 0 or 1) ({x})"),
153        }
154    }
155
156    /// 波長の番号(1 始まり、省けば None)→ 0 始まり
157    pub fn wave(&mut self, key: &str) -> Result<Option<usize>> {
158        match self.opt_count(key)? {
159            Some(0) => invalid!("setting {key} starts at 1"),
160            w => Ok(w.map(|w| w - 1)),
161        }
162    }
163
164    /// 読まなかった名前があれば誤り(綴りの誤りを黙って無視しない)
165    pub fn finish(self) -> Result<()> {
166        let unknown: Vec<&str> = self
167            .cfg
168            .keys()
169            .map(String::as_str)
170            .filter(|k| !self.used.contains(k))
171            .collect();
172        if !unknown.is_empty() {
173            invalid!("unknown setting: {}", unknown.join(", "));
174        }
175        Ok(())
176    }
177}
178
179/// 配列の値(行優先の平らな並び)
180#[derive(Debug, Clone, PartialEq)]
181pub enum Data {
182    F64(Vec<f64>),
183    C64(Vec<C64>),
184    Bool(Vec<bool>),
185}
186
187impl Data {
188    pub fn len(&self) -> usize {
189        match self {
190            Data::F64(v) => v.len(),
191            Data::C64(v) => v.len(),
192            Data::Bool(v) => v.len(),
193        }
194    }
195
196    pub fn is_empty(&self) -> bool {
197        self.len() == 0
198    }
199
200    pub fn dtype(&self) -> &'static str {
201        match self {
202            Data::F64(_) => "float64",
203            Data::C64(_) => "complex128",
204            Data::Bool(_) => "bool",
205        }
206    }
207}
208
209impl From<Vec<f64>> for Data {
210    fn from(v: Vec<f64>) -> Self {
211        Data::F64(v)
212    }
213}
214
215impl From<Vec<C64>> for Data {
216    fn from(v: Vec<C64>) -> Self {
217        Data::C64(v)
218    }
219}
220
221impl From<Vec<bool>> for Data {
222    fn from(v: Vec<bool>) -> Self {
223        Data::Bool(v)
224    }
225}
226
227/// 形つきの配列
228#[derive(Debug, Clone, PartialEq)]
229pub struct Array {
230    pub shape: Vec<usize>,
231    pub data: Data,
232}
233
234impl Array {
235    /// 形と値の数が合うか確かめて作る
236    pub fn new(shape: Vec<usize>, data: Data) -> Result<Self> {
237        let n: usize = shape.iter().product();
238        if n != data.len() {
239            invalid!(
240                "array shape {shape:?} doesn't match the {} values",
241                data.len()
242            );
243        }
244        Ok(Self { shape, data })
245    }
246
247    pub fn f64(shape: Vec<usize>, v: Vec<f64>) -> Result<Self> {
248        Self::new(shape, Data::F64(v))
249    }
250
251    pub fn c64(shape: Vec<usize>, v: Vec<C64>) -> Result<Self> {
252        Self::new(shape, Data::C64(v))
253    }
254
255    pub fn bool(shape: Vec<usize>, v: Vec<bool>) -> Result<Self> {
256        Self::new(shape, Data::Bool(v))
257    }
258
259    /// 2 次元の格子の値([`crate::grid::Grid2`])→ 形 (ny, nx) の配列(行優先のまま写す。座標は別の配列で渡す)。
260    /// 解析・拡張の 2 次元の出力はこれで作る
261    pub fn grid<T: Clone>(g: &crate::grid::Grid2<T>) -> Self
262    where
263        Data: From<Vec<T>>,
264    {
265        Self {
266            shape: vec![g.ny(), g.nx()],
267            data: Data::from(g.data().to_vec()),
268        }
269    }
270
271    /// 数 1 つ(形 [])
272    pub fn scalar(x: f64) -> Self {
273        Self {
274            shape: Vec::new(),
275            data: Data::F64(vec![x]),
276        }
277    }
278
279    pub fn as_f64(&self) -> Option<&[f64]> {
280        match &self.data {
281            Data::F64(v) => Some(v),
282            _ => None,
283        }
284    }
285
286    pub fn as_c64(&self) -> Option<&[C64]> {
287        match &self.data {
288            Data::C64(v) => Some(v),
289            _ => None,
290        }
291    }
292
293    pub fn as_bool(&self) -> Option<&[bool]> {
294        match &self.data {
295            Data::Bool(v) => Some(v),
296            _ => None,
297        }
298    }
299}
300
301/// 名前つきの配列(入力・出力)
302pub type Arrays = BTreeMap<String, Array>;
303
304/// 入力を読む補助(名前・型の確かめと、知らない名前の検出)
305pub struct ArrayReader<'a> {
306    arrs: &'a Arrays,
307    used: Vec<&'a str>,
308}
309
310impl<'a> ArrayReader<'a> {
311    pub fn new(arrs: &'a Arrays) -> Self {
312        Self {
313            arrs,
314            used: Vec::new(),
315        }
316    }
317
318    /// 名前の配列(省いてよい)
319    pub fn opt(&mut self, key: &str) -> Option<&'a Array> {
320        let (k, v) = self.arrs.get_key_value(key)?;
321        self.used.push(k);
322        Some(v)
323    }
324
325    /// 名前の配列(必須)
326    pub fn req(&mut self, key: &str) -> Result<&'a Array> {
327        match self.opt(key) {
328            Some(a) => Ok(a),
329            None => invalid!("no input {key}"),
330        }
331    }
332
333    /// float64 の配列(必須)→ (形, 値)
334    pub fn f64(&mut self, key: &str) -> Result<(&'a [usize], &'a [f64])> {
335        let a = self.req(key)?;
336        match a.as_f64() {
337            Some(v) => Ok((&a.shape, v)),
338            None => invalid!("input {key} must be float64 ({})", a.data.dtype()),
339        }
340    }
341
342    /// complex128 の配列(必須)→ (形, 値)
343    pub fn c64(&mut self, key: &str) -> Result<(&'a [usize], &'a [C64])> {
344        let a = self.req(key)?;
345        match a.as_c64() {
346            Some(v) => Ok((&a.shape, v)),
347            None => invalid!("input {key} must be complex128 ({})", a.data.dtype()),
348        }
349    }
350
351    /// 読まなかった名前があれば誤り
352    pub fn finish(self) -> Result<()> {
353        let unknown: Vec<&str> = self
354            .arrs
355            .keys()
356            .map(String::as_str)
357            .filter(|k| !self.used.contains(k))
358            .collect();
359        if !unknown.is_empty() {
360            invalid!("unknown input: {}", unknown.join(", "));
361        }
362        Ok(())
363    }
364}
365
366/// 視野の入力: 数 1 つなら番号(1 始まり)、2 個なら正規化視野 (hx, hy)
367pub fn field_sel(s: &System, a: &Array) -> Result<crate::FieldSel> {
368    let Some(v) = a.as_f64() else {
369        invalid!("the field must be a number");
370    };
371    match v {
372        [i] => {
373            let n = s.fields.len();
374            if i.fract() != 0.0 || *i < 1.0 || *i > n as f64 {
375                invalid!("the field must be 1 to {n} ({i})");
376            }
377            Ok(crate::FieldSel::Index(*i as usize - 1))
378        }
379        [hx, hy] => Ok(crate::FieldSel::Norm(*hx, *hy)),
380        _ => invalid!("the field must be one or two numbers ({} values)", v.len()),
381    }
382}
383
384/// 波長の番号(0 始まり)が系の範囲にあるか
385pub fn check_wave(s: &System, w: Option<usize>) -> Result<()> {
386    if let Some(w) = w {
387        if w >= s.wavelengths.len() {
388            invalid!(
389                "the wavelength must be 1 to {} ({})",
390                s.wavelengths.len(),
391                w + 1
392            );
393        }
394    }
395    Ok(())
396}
397
398/// 入出力の名前・形の説明(一覧・ヘルプ用。呼び出しの確かめは [`Instance::run`] が行う)。設定の説明は
399/// [`Plugin::params`] だけに書く(型・既定・単位つき)
400#[derive(Debug, Clone, Default, PartialEq)]
401pub struct Spec {
402    /// 1 行の説明
403    pub doc: String,
404    /// 入力: (名前, 説明)
405    pub inputs: Vec<(String, String)>,
406    /// 出力(名前・型・形・単位・説明)
407    pub outputs: Vec<OutputSpec>,
408    /// 系([`Context::system`])が要るか
409    pub needs_system: bool,
410}
411
412/// 出力の 1 つの配列の説明
413#[derive(Debug, Clone, Default, PartialEq)]
414pub struct OutputSpec {
415    pub name: String,
416    /// 要素の型: "float64"・"complex128"・"bool"
417    pub dtype: String,
418    /// 形("(2,)"・"(n, n)" など。1 つの値は "()"、決まった形が無ければ空)
419    pub shape: String,
420    /// 単位(mm・波 など。無ければ空)
421    pub unit: String,
422    pub doc: String,
423}
424
425impl OutputSpec {
426    pub fn new(name: &str, dtype: &str, shape: &str, unit: &str, doc: &str) -> Self {
427        OutputSpec {
428            name: name.into(),
429            dtype: dtype.into(),
430            shape: shape.into(),
431            unit: unit.into(),
432            doc: doc.into(),
433        }
434    }
435
436    /// 形が読めるか(dtype が 3 種のどれか、形は空か「()」か「(n, *形)」のような ASCII の名前・数をカンマでつないだもの、
437    /// 説明に角括弧が残っていない)。誤りは名前つきの文
438    pub fn check(&self) -> crate::Result<()> {
439        let n = &self.name;
440        if !matches!(self.dtype.as_str(), "float64" | "complex128" | "bool") {
441            return Err(format!("{n}: dtype {}", self.dtype).into());
442        }
443        let s = self.shape.as_str();
444        if !s.is_empty() && s != "()" {
445            let inner = s.strip_prefix('(').and_then(|x| x.strip_suffix(')'));
446            let ok = inner.is_some_and(|x| {
447                x.contains(',')
448                    && x.split(',')
449                        .map(str::trim)
450                        .filter(|d| !d.is_empty())
451                        .all(|d| {
452                            let d = d.trim_start_matches('*');
453                            !d.is_empty()
454                                && d != "0"
455                                && d.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
456                        })
457            });
458            if !ok {
459                return Err(format!("{n}: shape {s}").into());
460            }
461        }
462        if self.doc.contains('[') || self.doc.contains(']') {
463            return Err(format!("{n}: square brackets in the description {}", self.doc).into());
464        }
465        Ok(())
466    }
467
468    /// 説明の文から型・形・単位を取り出す: 「complex」「complex128」「bool」の語で型(無ければ float64)、カンマを含む
469    /// 最後の括弧(「(n, n)」)か「scalar」で形、最後の角括弧(「[mm]」)で単位。残りが説明
470    pub fn from_doc(name: &str, desc: &str) -> Self {
471        let mut d = desc.to_string();
472        let mut take = |pat: &str| -> bool {
473            match d.find(pat) {
474                Some(i) => {
475                    d.replace_range(i..i + pat.len(), "");
476                    true
477                }
478                None => false,
479            }
480        };
481        let dtype = if take("complex128") || take("complex") {
482            "complex128"
483        } else if take("bool") {
484            "bool"
485        } else {
486            take("float64");
487            "float64"
488        };
489        let mut unit = String::new();
490        if let (Some(a), Some(b)) = (d.rfind('['), d.rfind(']')) {
491            if a < b {
492                unit = d[a + '['.len_utf8()..b].trim().to_string();
493                d.replace_range(a..b + ']'.len_utf8(), "");
494            }
495        }
496        let mut shape = String::new();
497        let (mut from, mut last) = (0, None);
498        while let Some(a) = d[from..].find('(').map(|i| i + from) {
499            let Some(b) = d[a..].find(')').map(|i| i + a) else {
500                break;
501            };
502            if d[a..b].contains(',') {
503                last = Some((a, b));
504            }
505            from = b;
506        }
507        if let Some((a, b)) = last {
508            shape = d[a..=b].to_string();
509            d.replace_range(a..=b, "");
510        }
511        if shape.is_empty() && d.contains("scalar") {
512            shape = "()".into();
513            d = d.replacen("scalar", "", 1);
514        }
515        let d = d.split_whitespace().collect::<Vec<_>>().join(" ");
516        let doc = d
517            .replace(" 、", "、")
518            .replace(" ,", ",")
519            .trim_matches(|c: char| c == '、' || c == ',' || c.is_whitespace())
520            .to_string();
521        OutputSpec {
522            name: name.into(),
523            dtype: dtype.into(),
524            shape,
525            unit,
526            doc,
527        }
528    }
529}
530
531/// 設定の項目の型(GUI の欄を作る)
532#[derive(Debug, Clone, PartialEq)]
533pub enum ParamType {
534    /// 実数
535    Num,
536    /// 0 以上の整数
537    Count,
538    /// 真偽([`ConfigReader::flag`]。既定値は [`Value::Bool`])
539    Flag,
540    /// 文字列
541    Str,
542    /// 選択肢の文字列
543    Choice(Vec<String>),
544    /// 数の並び(`len` は個数の上限。1 個なら全部に同じ値などの決まりは説明に書く)
545    Nums { len: Option<usize> },
546}
547
548impl ParamType {
549    pub fn as_str(&self) -> &'static str {
550        match self {
551            ParamType::Num => "num",
552            ParamType::Count => "count",
553            ParamType::Flag => "flag",
554            ParamType::Str => "str",
555            ParamType::Choice(_) => "choice",
556            ParamType::Nums { .. } => "nums",
557        }
558    }
559}
560
561/// 設定の 1 項目の説明(名前・型・既定・単位・説明)。[`Plugin::params`] で返す
562#[derive(Debug, Clone, PartialEq)]
563pub struct ParamSpec {
564    /// 設定の名前(入れ子は「.」でつなぐ。例 `mla.pitch`)
565    pub name: String,
566    pub ty: ParamType,
567    /// 既定値(None は省けば自動で決まる・使わない)
568    pub default: Option<Value>,
569    /// 単位(mm・µm など。無ければ空)
570    pub unit: String,
571    /// 1 行の説明
572    pub doc: String,
573}
574
575impl ParamSpec {
576    pub fn new(name: &str, ty: ParamType, default: Option<Value>, unit: &str, doc: &str) -> Self {
577        ParamSpec {
578            name: name.into(),
579            ty,
580            default,
581            unit: unit.into(),
582            doc: doc.into(),
583        }
584    }
585}
586
587/// 呼び出しの文脈: 配列のほかに渡すもの(系・膜)。配列だけのプラグインは見ない
588#[derive(Clone, Copy, Default)]
589pub struct Context<'a> {
590    /// 系(追跡するプラグイン用)
591    pub system: Option<&'a Arc<System>>,
592    /// 系の膜(偏光追跡で使う。None なら膜なし)
593    pub coatings: Option<&'a Coatings>,
594}
595
596impl<'a> Context<'a> {
597    /// 系だけの文脈
598    pub fn with_system(system: &'a Arc<System>) -> Self {
599        Self {
600            system: Some(system),
601            coatings: None,
602        }
603    }
604
605    /// 系(なければ誤り)
606    pub fn system(&self) -> Result<&'a System> {
607        match self.system {
608            Some(s) => Ok(s),
609            None => invalid!("this plugin needs a system"),
610        }
611    }
612}
613
614/// プラグイン(設定から [`Instance`] を作る)
615pub trait Plugin: Send + Sync {
616    /// 登録の名前
617    fn name(&self) -> &str;
618    fn kind(&self) -> Kind;
619    /// 入出力の説明
620    fn spec(&self) -> Spec {
621        Spec::default()
622    }
623    /// 設定の項目の説明(名前・型・既定値・単位)。設定の説明はここだけ(一覧・GUI の欄・Python の plugin_spec)
624    fn params(&self) -> Vec<ParamSpec> {
625        Vec::new()
626    }
627    /// 設定を確かめて呼び出しの準備をする
628    fn prepare(&self, config: &Config) -> Result<Box<dyn Instance>>;
629}
630
631/// 設定の決まったプラグイン(呼び出しの単位)
632pub trait Instance: Send + Sync {
633    /// 入力から出力を作る(状態なし)
634    fn run(&self, ctx: &Context<'_>, inputs: &Arrays) -> Result<Arrays>;
635
636    /// 線形化: [`Instance::run`] と同じ出力と、入力の微分 1 方向から出力の微分を作る [`Linear`]。多くの方向の微分を
637    /// 流すとき、解析を 1 回で済ませる口。既定は None(この口が無い。呼ぶ側は微分を run の入力に渡す)
638    fn linearize(
639        &self,
640        _ctx: &Context<'_>,
641        _inputs: &Arrays,
642    ) -> Result<Option<(Arrays, Box<dyn Linear + '_>)>> {
643        Ok(None)
644    }
645
646    /// 具体の型へ戻す口(上の層が、配列のほかに型の口を持つ実装を見分けて直接呼ぶ用)。既定は None
647    fn as_any(&self) -> Option<&dyn std::any::Any> {
648        None
649    }
650}
651
652/// [`Instance::linearize`] の線形の写像
653pub trait Linear: Send + Sync {
654    /// 入力の微分 1 方向(名前・形はプラグインの決めたもの)から出力の微分
655    fn apply(&self, d: &Arrays) -> Result<Arrays>;
656}
657
658/// 名前 → プラグイン
659#[derive(Clone, Default)]
660pub struct Registry {
661    map: BTreeMap<String, Arc<dyn Plugin>>,
662}
663
664impl Registry {
665    pub fn new() -> Self {
666        Self::default()
667    }
668
669    /// 登録する(同じ名前は差し替える)
670    pub fn register(&mut self, p: Arc<dyn Plugin>) {
671        self.map.insert(p.name().to_string(), p);
672    }
673
674    /// 外す(あれば true)
675    pub fn unregister(&mut self, name: &str) -> bool {
676        self.map.remove(name).is_some()
677    }
678
679    pub fn get(&self, name: &str) -> Result<Arc<dyn Plugin>> {
680        match self.map.get(name) {
681            Some(p) => Ok(p.clone()),
682            None => invalid!(
683                "no plugin {name} (registered: {})",
684                self.map.keys().cloned().collect::<Vec<_>>().join(", ")
685            ),
686        }
687    }
688
689    /// 登録のプラグイン(名前の順)
690    pub fn plugins(&self) -> impl Iterator<Item = &Arc<dyn Plugin>> {
691        self.map.values()
692    }
693
694    /// 登録の (名前, 種類) の一覧(名前の順)
695    pub fn list(&self) -> Vec<(String, Kind)> {
696        self.map
697            .iter()
698            .map(|(k, p)| (k.clone(), p.kind()))
699            .collect()
700    }
701
702    /// 名前と設定から呼び出しの準備
703    pub fn prepare(&self, name: &str, config: &Config) -> Result<Box<dyn Instance>> {
704        self.get(name)?.prepare(config)
705    }
706}
707
708/// 同じ準備で多数の入力を呼ぶ(入力ごとに独立、スレッド数は [`crate::with_threads`] に従う)。
709/// 結果は入力の順で、スレッド数によらず同じビット
710pub fn run_many(inst: &dyn Instance, ctx: &Context<'_>, inputs: &[Arrays]) -> Vec<Result<Arrays>> {
711    crate::par::map(inputs, |a| inst.run(ctx, a))
712}
713
714#[cfg(test)]
715mod tests {
716    use super::*;
717
718    /// 入力 x を k 倍して和も返す、試験用のプラグイン
719    struct Scale;
720    struct ScaleInst(f64);
721
722    impl Plugin for Scale {
723        fn name(&self) -> &str {
724            "scale"
725        }
726        fn kind(&self) -> Kind {
727            Kind::Analysis
728        }
729        fn prepare(&self, config: &Config) -> Result<Box<dyn Instance>> {
730            let mut r = ConfigReader::new(config);
731            let k = r.num("k", 1.0)?;
732            r.finish()?;
733            Ok(Box::new(ScaleInst(k)))
734        }
735    }
736
737    impl Instance for ScaleInst {
738        fn run(&self, _ctx: &Context<'_>, inputs: &Arrays) -> Result<Arrays> {
739            let mut r = ArrayReader::new(inputs);
740            let (s, x) = r.f64("x")?;
741            r.finish()?;
742            let y: Vec<f64> = x.iter().map(|v| v * self.0).collect();
743            let sum = y.iter().sum();
744            Ok(Arrays::from([
745                ("y".into(), Array::f64(s.to_vec(), y)?),
746                ("sum".into(), Array::scalar(sum)),
747            ]))
748        }
749    }
750
751    fn input(x: Vec<f64>) -> Arrays {
752        Arrays::from([("x".into(), Array::f64(vec![x.len()], x).unwrap())])
753    }
754
755    #[test]
756    fn registry_and_run() {
757        let mut reg = Registry::new();
758        reg.register(Arc::new(Scale));
759        assert_eq!(reg.list(), vec![("scale".to_string(), Kind::Analysis)]);
760        let inst = reg
761            .prepare("scale", &Config::from([("k".into(), Value::Num(2.0))]))
762            .unwrap();
763        let out = inst
764            .run(&Context::default(), &input(vec![1.0, 2.5]))
765            .unwrap();
766        assert_eq!(out["y"].as_f64().unwrap(), &[2.0, 5.0]);
767        assert_eq!(out["sum"].shape, Vec::<usize>::new());
768        assert!(reg.get("none").is_err());
769        assert!(reg.unregister("scale") && reg.list().is_empty());
770    }
771
772    #[test]
773    fn rejects_unknown_and_wrong_types() {
774        let p = Scale;
775        assert!(p
776            .prepare(&Config::from([("kk".into(), Value::Num(2.0))]))
777            .is_err());
778        assert!(p
779            .prepare(&Config::from([("k".into(), Value::Str("a".into()))]))
780            .is_err());
781        let inst = p.prepare(&Config::new()).unwrap();
782        let mut a = input(vec![1.0]);
783        a.insert("z".into(), Array::scalar(0.0));
784        assert!(inst.run(&Context::default(), &a).is_err());
785        let a = Arrays::from([(
786            "x".into(),
787            Array::c64(vec![1], vec![C64::new(1.0, 0.0)]).unwrap(),
788        )]);
789        assert!(inst.run(&Context::default(), &a).is_err());
790        assert!(Array::f64(vec![2, 2], vec![0.0; 3]).is_err());
791        assert!(Kind::parse("x").is_err() && Kind::parse("detector").unwrap() == Kind::Detector);
792    }
793
794    /// 出力の説明の文から型・形・単位を取り出す
795    #[test]
796    fn output_spec_from_doc() {
797        let o = OutputSpec::from_doc("w", "OPD (n, n) [波]、外は NaN");
798        assert_eq!(
799            (
800                o.dtype.as_str(),
801                o.shape.as_str(),
802                o.unit.as_str(),
803                o.doc.as_str()
804            ),
805            ("float64", "(n, n)", "波", "OPD、外は NaN")
806        );
807        let o = OutputSpec::from_doc("c", "complex128 (4, n)(spectral)");
808        assert_eq!(
809            (o.dtype.as_str(), o.shape.as_str(), o.doc.as_str()),
810            ("complex128", "(4, n)", "(spectral)")
811        );
812        let o = OutputSpec::from_doc("z4", "scalar mm");
813        assert_eq!((o.shape.as_str(), o.doc.as_str()), ("()", "mm"));
814        let o = OutputSpec::from_doc("index", "番号 (i, j) (n, 2)");
815        assert_eq!(
816            (o.shape.as_str(), o.doc.as_str()),
817            ("(n, 2)", "番号 (i, j)")
818        );
819        let o = OutputSpec::from_doc("used", "復元に使ったか (n,) bool");
820        assert_eq!((o.dtype.as_str(), o.shape.as_str()), ("bool", "(n,)"));
821        let o = OutputSpec::from_doc("pilot", "(ax, ay, curv)");
822        assert_eq!(o.shape, "(ax, ay, curv)");
823    }
824
825    /// 真偽は true・false か 0・1、整数の欄に NaN を書くと「省略」でなく誤り
826    #[test]
827    fn flags_and_counts() {
828        let c = Config::from([
829            ("a".into(), Value::Bool(true)),
830            ("b".into(), Value::Num(0.0)),
831            ("n".into(), Value::Num(f64::NAN)),
832        ]);
833        let mut r = ConfigReader::new(&c);
834        assert!(r.flag("a", false).unwrap());
835        assert!(!r.flag("b", true).unwrap());
836        assert!(r.flag("z", true).unwrap());
837        assert!(r.opt_count("n").is_err());
838        assert!(r.opt_num("n").is_err());
839        assert_eq!(r.opt_count("m").unwrap(), None);
840        r.finish().unwrap();
841    }
842
843    #[test]
844    fn run_many_is_ordered_and_thread_independent() {
845        let inst = Scale.prepare(&Config::new()).unwrap();
846        let inputs: Vec<Arrays> = (0..40).map(|i| input(vec![i as f64; 3])).collect();
847        let a = crate::with_threads(Some(1), || {
848            run_many(inst.as_ref(), &Context::default(), &inputs)
849        });
850        let b = crate::with_threads(Some(4), || {
851            run_many(inst.as_ref(), &Context::default(), &inputs)
852        });
853        assert_eq!(a, b);
854        assert_eq!(a[7].as_ref().unwrap()["sum"].as_f64().unwrap(), &[21.0]);
855    }
856}