sim-lib-femm-function 0.1.0

SIM workspace package for sim lib femm function.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Library registration that exposes FEMM callables to the runtime.
//!
//! Defines the `Lib` that installs the FEMM function exports and the built-in
//! fixture models so the runtime can call them by name.

use std::{any::Any, sync::Arc};

use sim_kernel::{
    AbiVersion, Args, Callable, ClassRef, Cx, DefaultFactory, Dependency, Error, Export, Expr,
    Factory, Lib, LibManifest, LibTarget, Linker, Object, RawArgs, Result as KernelResult, Symbol,
    Value, Version,
};
use sim_lib_femm_core::{FemmLimits, ParamSet};
use sim_lib_femm_field::Projection;
use sim_lib_femm_fixtures::{
    air_core_solenoid, field_as_number_line_integration, gapped_ei_core_inductor,
    parallel_plate_capacitor, plunger_actuator_ode, slab_heat_conductor,
    uniform_conductor_resistance,
};
use sim_lib_femm_mesh::FemmModel;
use sim_lib_femm_post::QuantitySpec;

use crate::model_value::{ModelValue, model_value};
use crate::{FemmCall, FemmCallable, ModelCallable, OutputQuery, femm_as_func};

/// The runtime library that installs the FEMM function exports.
///
/// Registers `femm/model`, `femm/eval`, `femm/as-func`, `femm/field`, and
/// `femm/grad` as callables so the runtime can build, evaluate, and
/// differentiate models by name. See the [crate README](index.html).
pub struct FemmFunctionLib;

impl FemmFunctionLib {
    /// Creates the library installer.
    pub fn new() -> Self {
        Self
    }
}

impl Default for FemmFunctionLib {
    fn default() -> Self {
        Self::new()
    }
}

impl Lib for FemmFunctionLib {
    fn manifest(&self) -> LibManifest {
        LibManifest {
            id: Symbol::qualified("femm", "function"),
            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
            abi: AbiVersion { major: 0, minor: 1 },
            target: LibTarget::HostRegistered,
            requires: vec![Dependency {
                id: Symbol::qualified("femm", "field"),
                minimum_version: None,
            }],
            capabilities: Vec::new(),
            exports: function_symbols()
                .into_iter()
                .map(|symbol| Export::Function {
                    symbol,
                    function_id: None,
                })
                .collect(),
        }
    }

    fn load(&self, _cx: &mut sim_kernel::LoadCx, linker: &mut Linker<'_>) -> KernelResult<()> {
        for symbol in function_symbols() {
            linker.function_value(
                symbol.clone(),
                DefaultFactory.opaque(Arc::new(FemmFunctionValue { symbol }))?,
            )?;
        }
        Ok(())
    }
}

fn function_symbols() -> Vec<Symbol> {
    vec![
        Symbol::qualified("femm", "model"),
        Symbol::qualified("femm", "eval"),
        Symbol::qualified("femm", "as-func"),
        Symbol::qualified("femm", "field"),
        Symbol::qualified("femm", "grad"),
    ]
}

#[derive(Clone)]
struct FemmFunctionValue {
    symbol: Symbol,
}

impl Object for FemmFunctionValue {
    fn display(&self, _cx: &mut Cx) -> KernelResult<String> {
        Ok(format!("#<function {}>", self.symbol))
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl sim_kernel::ObjectCompat for FemmFunctionValue {
    fn class(&self, cx: &mut Cx) -> KernelResult<ClassRef> {
        if let Some(class) = cx
            .registry()
            .class_by_symbol(&Symbol::qualified("core", "Function"))
        {
            return Ok(class.clone());
        }
        DefaultFactory.class_stub(
            sim_kernel::CORE_FUNCTION_CLASS_ID,
            Symbol::qualified("core", "Function"),
        )
    }
    fn as_expr(&self, _cx: &mut Cx) -> KernelResult<Expr> {
        Ok(Expr::Symbol(self.symbol.clone()))
    }
    fn as_callable(&self) -> Option<&dyn Callable> {
        Some(self)
    }
}

impl Callable for FemmFunctionValue {
    fn call(&self, cx: &mut Cx, args: Args) -> KernelResult<Value> {
        match self.symbol.to_string().as_str() {
            "femm/model" => call_model(cx, args.into_vec()),
            "femm/eval" => call_eval(cx, args.into_vec()),
            "femm/as-func" => call_as_func(cx, args.into_vec()),
            "femm/field" => call_field(cx, args.into_vec()),
            "femm/grad" => call_grad(cx, args.into_vec()),
            _ => Err(Error::Eval(format!(
                "Unknown FEMM function {}",
                self.symbol
            ))),
        }
    }

    fn call_exprs(&self, cx: &mut Cx, args: RawArgs) -> KernelResult<Value> {
        let values = args
            .into_exprs()
            .into_iter()
            .map(|expr| cx.eval_expr(expr))
            .collect::<KernelResult<Vec<_>>>()?;
        self.call(cx, Args::new(values))
    }
}

fn call_model(cx: &mut Cx, args: Vec<Value>) -> KernelResult<Value> {
    let model = match args.as_slice() {
        [] => parallel_plate_capacitor(),
        [name] => example_model(symbolish_or_string(cx, name)?.as_str())
            .ok_or_else(|| Error::Eval("unknown FEMM example model".to_owned()))?,
        _ => {
            return Err(Error::Eval(
                "femm/model expects zero or one example name".to_owned(),
            ));
        }
    };
    cx.factory().opaque(Arc::new(model_value(model)))
}

fn call_eval(cx: &mut Cx, args: Vec<Value>) -> KernelResult<Value> {
    let [model, query, params] = args.as_slice() else {
        return Err(Error::Eval(
            "femm/eval expects model, query, params".to_owned(),
        ));
    };
    let model = model_from_value(model)?;
    let query = scalar_query_from_value(cx, query)?;
    let params = params_from_value(cx, params)?;
    ModelCallable { model }
        .eval(
            cx,
            FemmCall {
                params,
                query,
                want_grad: None,
                limits: FemmLimits::default(),
            },
        )
        .map(|out| out.value)
        .map_err(Error::from)
}

fn call_as_func(cx: &mut Cx, args: Vec<Value>) -> KernelResult<Value> {
    let [model, vars, query] = args.as_slice() else {
        return Err(Error::Eval(
            "femm/as-func expects model, vars, query".to_owned(),
        ));
    };
    let model = model_from_value(model)?;
    let vars = symbol_list_from_value(cx, vars)?;
    let query = scalar_query_from_value(cx, query)?;
    cx.factory()
        .opaque(Arc::new(femm_as_func(model, vars, query)))
}

fn call_field(cx: &mut Cx, args: Vec<Value>) -> KernelResult<Value> {
    let [model, projection, params] = args.as_slice() else {
        return Err(Error::Eval(
            "femm/field expects model, projection, params".to_owned(),
        ));
    };
    let model = model_from_value(model)?;
    let projection = projection_from_value(cx, projection)?;
    let params = params_from_value(cx, params)?;
    ModelCallable { model }
        .eval(
            cx,
            FemmCall {
                params,
                query: OutputQuery::Field(projection),
                want_grad: None,
                limits: FemmLimits::default(),
            },
        )
        .map(|out| out.value)
        .map_err(Error::from)
}

fn call_grad(cx: &mut Cx, args: Vec<Value>) -> KernelResult<Value> {
    let [model, query, wrt, params] = args.as_slice() else {
        return Err(Error::Eval(
            "femm/grad expects model, query, wrt, params".to_owned(),
        ));
    };
    let model = model_from_value(model)?;
    let query = scalar_query_from_value(cx, query)?;
    let wrt = symbol_list_from_value(cx, wrt)?;
    let params = params_from_value(cx, params)?;
    let gradient = gradient_pairs(cx, &ModelCallable { model }, query, params, &wrt)?;
    cx.factory().list(
        gradient
            .into_iter()
            .map(|(symbol, value)| {
                cx.factory().list(vec![
                    cx.factory().symbol(symbol)?,
                    cx.factory()
                        .number_literal(Symbol::qualified("numbers", "f64"), value.to_string())?,
                ])
            })
            .collect::<KernelResult<Vec<_>>>()?,
    )
}

fn gradient_pairs(
    cx: &mut Cx,
    callable: &ModelCallable,
    query: OutputQuery,
    params: ParamSet,
    wrt: &[Symbol],
) -> KernelResult<Vec<(Symbol, f64)>> {
    let mut out = Vec::new();
    for symbol in wrt {
        let base_value = params
            .get(symbol)
            .ok_or_else(|| Error::Eval(format!("unknown FEMM parameter {symbol}")))?;
        let x = sim_lib_femm_core::value_as_f64(cx, base_value).map_err(Error::from)?;
        let h = 1.0e-6;
        let plus = replace_param(cx, &params, symbol, x + h)?;
        let minus = replace_param(cx, &params, symbol, x - h)?;
        let plus_value = eval_scalar(cx, callable, query.clone(), plus)?;
        let minus_value = eval_scalar(cx, callable, query.clone(), minus)?;
        out.push((symbol.clone(), (plus_value - minus_value) / (2.0 * h)));
    }
    Ok(out)
}

fn model_from_value(value: &Value) -> KernelResult<FemmModel> {
    value
        .object()
        .downcast_ref::<ModelValue>()
        .map(|model| model.model.clone())
        .ok_or_else(|| Error::Eval("expected FEMM model value".to_owned()))
}

fn example_model(name: &str) -> Option<FemmModel> {
    Some(match name {
        "parallel-plate-capacitor" => parallel_plate_capacitor(),
        "slab-heat-conductor" => slab_heat_conductor(),
        "uniform-conductor-resistance" => uniform_conductor_resistance(),
        "air-core-solenoid" => air_core_solenoid(),
        "gapped-ei-core-inductor" => gapped_ei_core_inductor(),
        "plunger-actuator-ode" => plunger_actuator_ode(),
        "field-as-number-line-integration" => field_as_number_line_integration(),
        _ => return None,
    })
}

fn symbolish_or_string(cx: &mut Cx, value: &Value) -> KernelResult<String> {
    match value.object().as_expr(cx)? {
        Expr::Symbol(symbol) => Ok(symbol.to_string()),
        Expr::String(text) => Ok(text),
        Expr::Quote { expr, .. } => match *expr {
            Expr::Symbol(symbol) => Ok(symbol.to_string()),
            _ => Err(Error::Eval("expected symbol or string".to_owned())),
        },
        _ => Err(Error::Eval("expected symbol or string".to_owned())),
    }
}

fn symbol_list_from_value(cx: &mut Cx, value: &Value) -> KernelResult<Vec<Symbol>> {
    match value.object().as_expr(cx)? {
        Expr::List(items) | Expr::Vector(items) => items
            .into_iter()
            .map(expr_to_symbol)
            .collect::<KernelResult<Vec<_>>>(),
        _ => Err(Error::Eval("expected symbol list".to_owned())),
    }
}

fn expr_to_symbol(expr: Expr) -> KernelResult<Symbol> {
    match expr {
        Expr::Symbol(symbol) => Ok(symbol),
        Expr::Quote { expr, .. } => match *expr {
            Expr::Symbol(symbol) => Ok(symbol),
            _ => Err(Error::Eval("expected quoted symbol".to_owned())),
        },
        _ => Err(Error::Eval("expected symbol".to_owned())),
    }
}

fn params_from_value(cx: &mut Cx, value: &Value) -> KernelResult<ParamSet> {
    match value.object().as_expr(cx)? {
        Expr::Map(entries) => Ok(ParamSet::new(
            entries
                .into_iter()
                .map(|(key, value_expr)| Ok((expr_to_symbol(key)?, cx.eval_expr(value_expr)?)))
                .collect::<KernelResult<Vec<_>>>()?,
        )),
        Expr::List(items) | Expr::Vector(items) => Ok(ParamSet::new(
            items
                .into_iter()
                .map(|item| match item {
                    Expr::List(pair) | Expr::Vector(pair) if pair.len() == 2 => Ok((
                        expr_to_symbol(pair[0].clone())?,
                        cx.eval_expr(pair[1].clone())?,
                    )),
                    _ => Err(Error::Eval(
                        "expected [symbol value] param entry".to_owned(),
                    )),
                })
                .collect::<KernelResult<Vec<_>>>()?,
        )),
        Expr::Nil => Ok(ParamSet::default()),
        _ => Err(Error::Eval(
            "expected parameter table or pair list".to_owned(),
        )),
    }
}

fn scalar_query_from_value(cx: &mut Cx, value: &Value) -> KernelResult<OutputQuery> {
    Ok(OutputQuery::Quantity(QuantitySpec::Custom {
        name: Symbol::new("q"),
        expr: value.object().as_expr(cx)?,
    }))
}

fn projection_from_value(cx: &mut Cx, value: &Value) -> KernelResult<Projection> {
    match symbolish_or_string(cx, value)?.as_str() {
        "potential" => Ok(Projection::Potential),
        "bx" => Ok(Projection::Bx),
        "by" => Ok(Projection::By),
        "bmag" => Ok(Projection::Bmag),
        "ex" => Ok(Projection::Ex),
        "ey" => Ok(Projection::Ey),
        "emag" => Ok(Projection::Emag),
        "heat-flux-mag" => Ok(Projection::HeatFluxMag),
        other => Err(Error::Eval(format!("unknown FEMM projection {other}"))),
    }
}

fn replace_param(
    cx: &mut Cx,
    params: &ParamSet,
    name: &Symbol,
    value: f64,
) -> KernelResult<ParamSet> {
    let mut entries = params.entries.clone();
    for (symbol, slot) in &mut entries {
        if symbol == name {
            *slot = cx
                .factory()
                .number_literal(Symbol::qualified("numbers", "f64"), value.to_string())?;
        }
    }
    Ok(ParamSet::new(entries))
}

fn eval_scalar(
    cx: &mut Cx,
    callable: &ModelCallable,
    query: OutputQuery,
    params: ParamSet,
) -> KernelResult<f64> {
    let eval = callable
        .eval(
            cx,
            FemmCall {
                params,
                query,
                want_grad: None,
                limits: FemmLimits::default(),
            },
        )
        .map_err(Error::from)?;
    sim_lib_femm_core::value_as_f64(cx, &eval.value).map_err(Error::from)
}