1use std::collections::BTreeMap;
18use std::sync::Arc;
19
20use crate::coating::{Coatings, C64};
21use crate::{invalid, Result, System};
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
25pub enum Kind {
26 Detector,
28 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#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
51#[serde(untagged)]
52#[derive(schemars::JsonSchema)]
53pub enum Value {
54 Num(f64),
55 Bool(bool),
57 Str(String),
58 Nums(Vec<f64>),
60}
61
62pub type Config = BTreeMap<String, Value>;
64
65pub 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 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 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 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 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 pub fn count(&mut self, key: &str, default: usize) -> Result<usize> {
128 Ok(self.opt_count(key)?.unwrap_or(default))
129 }
130
131 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 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 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 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#[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#[derive(Debug, Clone, PartialEq)]
229pub struct Array {
230 pub shape: Vec<usize>,
231 pub data: Data,
232}
233
234impl Array {
235 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 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 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
301pub type Arrays = BTreeMap<String, Array>;
303
304pub 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 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 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 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 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 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
366pub 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
384pub 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#[derive(Debug, Clone, Default, PartialEq)]
401pub struct Spec {
402 pub doc: String,
404 pub inputs: Vec<(String, String)>,
406 pub outputs: Vec<OutputSpec>,
408 pub needs_system: bool,
410}
411
412#[derive(Debug, Clone, Default, PartialEq)]
414pub struct OutputSpec {
415 pub name: String,
416 pub dtype: String,
418 pub shape: String,
420 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 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 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#[derive(Debug, Clone, PartialEq)]
533pub enum ParamType {
534 Num,
536 Count,
538 Flag,
540 Str,
542 Choice(Vec<String>),
544 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#[derive(Debug, Clone, PartialEq)]
563pub struct ParamSpec {
564 pub name: String,
566 pub ty: ParamType,
567 pub default: Option<Value>,
569 pub unit: String,
571 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#[derive(Clone, Copy, Default)]
589pub struct Context<'a> {
590 pub system: Option<&'a Arc<System>>,
592 pub coatings: Option<&'a Coatings>,
594}
595
596impl<'a> Context<'a> {
597 pub fn with_system(system: &'a Arc<System>) -> Self {
599 Self {
600 system: Some(system),
601 coatings: None,
602 }
603 }
604
605 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
614pub trait Plugin: Send + Sync {
616 fn name(&self) -> &str;
618 fn kind(&self) -> Kind;
619 fn spec(&self) -> Spec {
621 Spec::default()
622 }
623 fn params(&self) -> Vec<ParamSpec> {
625 Vec::new()
626 }
627 fn prepare(&self, config: &Config) -> Result<Box<dyn Instance>>;
629}
630
631pub trait Instance: Send + Sync {
633 fn run(&self, ctx: &Context<'_>, inputs: &Arrays) -> Result<Arrays>;
635
636 fn linearize(
639 &self,
640 _ctx: &Context<'_>,
641 _inputs: &Arrays,
642 ) -> Result<Option<(Arrays, Box<dyn Linear + '_>)>> {
643 Ok(None)
644 }
645
646 fn as_any(&self) -> Option<&dyn std::any::Any> {
648 None
649 }
650}
651
652pub trait Linear: Send + Sync {
654 fn apply(&self, d: &Arrays) -> Result<Arrays>;
656}
657
658#[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 pub fn register(&mut self, p: Arc<dyn Plugin>) {
671 self.map.insert(p.name().to_string(), p);
672 }
673
674 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 pub fn plugins(&self) -> impl Iterator<Item = &Arc<dyn Plugin>> {
691 self.map.values()
692 }
693
694 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 pub fn prepare(&self, name: &str, config: &Config) -> Result<Box<dyn Instance>> {
704 self.get(name)?.prepare(config)
705 }
706}
707
708pub 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 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 #[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 #[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}