lensbench_design/
plugin_term.rs1use std::sync::Arc;
5
6use lensbench_core::plugin::{Array, Arrays, Config, Context, Instance, Value as PValue};
7use lensbench_core::{Error, Result, System};
8use lensbench_optim::UserTerm;
9use serde_json::Value;
10
11pub struct PluginTerm {
12 label: String,
13 inst: Box<dyn Instance>,
14 inputs: Arrays,
15 output: String,
16 index: Option<usize>,
17 target: Vec<f64>,
18 rows: usize,
19}
20
21impl PluginTerm {
22 pub fn new(
24 name: &str,
25 args: &Config,
26 inputs: Arrays,
27 output: &str,
28 index: Option<usize>,
29 target: Vec<f64>,
30 s: &System,
31 ) -> Result<PluginTerm> {
32 let inst = crate::plugins::prepare(name, args)?;
33 let mut t = PluginTerm {
34 label: format!("plugin {name}.{output}"),
35 inst,
36 inputs,
37 output: output.to_string(),
38 index,
39 target: vec![],
40 rows: 0,
41 };
42 let v = t.values(s)?;
43 t.rows = v.len();
44 t.target = match target.len() {
45 0 => vec![0.0; t.rows],
46 1 => vec![target[0]; t.rows],
47 n if n == t.rows => target,
48 n => {
49 return Err(Error::Invalid(format!(
50 "{}: target has {n} values (the output has {})",
51 t.label, t.rows
52 )))
53 }
54 };
55 Ok(t)
56 }
57
58 pub fn values(&self, s: &System) -> Result<Vec<f64>> {
60 let sys = Arc::new(s.clone());
61 let out = self.inst.run(&Context::with_system(&sys), &self.inputs)?;
62 let a = out.get(&self.output).ok_or_else(|| {
63 Error::Invalid(format!(
64 "{}: no output {} ({})",
65 self.label,
66 self.output,
67 out.keys().cloned().collect::<Vec<_>>().join(", ")
68 ))
69 })?;
70 let v = a
71 .as_f64()
72 .ok_or_else(|| Error::Invalid(format!("{}: the output is not real", self.label)))?;
73 Ok(match self.index {
74 None => v.to_vec(),
75 Some(i) => vec![*v.get(i).ok_or_else(|| {
76 Error::Invalid(format!(
77 "{}: index {i} (the output has {} elements)",
78 self.label,
79 v.len()
80 ))
81 })?],
82 })
83 }
84}
85
86impl UserTerm for PluginTerm {
87 fn name(&self) -> &str {
88 &self.label
89 }
90 fn rows(&self) -> usize {
91 self.rows
92 }
93 fn eval(&self, systems: &[&System]) -> Result<Vec<Vec<f64>>> {
94 lensbench_core::par::map(systems, |s| {
96 let v = self.values(s)?;
97 if v.len() != self.rows {
98 return Err(Error::Invalid(format!(
99 "{}: output has {} values (expected {})",
100 self.label,
101 v.len(),
102 self.rows
103 )));
104 }
105 Ok(v.iter().zip(&self.target).map(|(x, t)| x - t).collect())
106 })
107 .into_iter()
108 .collect()
109 }
110}
111
112pub fn config_of(v: Option<&Value>) -> lensbench_core::Result<Config> {
114 let mut c = Config::new();
115 let Some(v) = v else { return Ok(c) };
116 let m = v
117 .as_object()
118 .ok_or_else(|| format!("args must be an object of name: value ({v})"))?;
119 for (k, x) in m {
120 let p = match x {
121 Value::Number(n) => PValue::Num(n.as_f64().unwrap_or(f64::NAN)),
122 Value::String(s) => PValue::Str(s.clone()),
123 Value::Array(a) => PValue::Nums(
124 a.iter()
125 .map(|y| {
126 y.as_f64()
127 .ok_or_else(|| format!("args {k} must be a list of numbers ({x})"))
128 })
129 .collect::<std::result::Result<_, _>>()?,
130 ),
131 _ => {
132 return Err(
133 format!("args {k} must be a number, string or list of numbers ({x})").into(),
134 )
135 }
136 };
137 c.insert(k.clone(), p);
138 }
139 Ok(c)
140}
141
142pub fn arrays_of(v: Option<&Value>) -> lensbench_core::Result<Arrays> {
144 let mut a = Arrays::new();
145 let Some(v) = v else { return Ok(a) };
146 let m = v
147 .as_object()
148 .ok_or_else(|| format!("inputs must be an object of name: value ({v})"))?;
149 for (k, x) in m {
150 a.insert(k.clone(), array_of(k, x)?);
151 }
152 Ok(a)
153}
154
155pub fn array_of(k: &str, x: &Value) -> lensbench_core::Result<Array> {
156 match x {
157 Value::Number(n) => Ok(Array::scalar(n.as_f64().unwrap_or(f64::NAN))),
158 Value::Array(v) => {
159 let d: Vec<f64> = v
160 .iter()
161 .map(|y| {
162 y.as_f64()
163 .ok_or_else(|| format!("input {k} must be a list of numbers ({x})"))
164 })
165 .collect::<std::result::Result<_, _>>()?;
166 Ok(Array::f64(vec![d.len()], d)?)
167 }
168 _ => Err(format!("input {k} must be a number or a list of numbers ({x})").into()),
169 }
170}