feynkit_model/scalar_bindings.rs
1//! Exact scalar specialization shared by native model consumers.
2
3use std::collections::BTreeMap;
4
5use symbolica::{
6 atom::{Atom, AtomCore, Symbol},
7 domains::rational::Rational,
8 id::{Pattern, Replacement},
9 symbol,
10};
11
12use crate::{Model, ModelError, ParameterCard, ParameterNature};
13
14/// Close a set of named scalar definitions using literal Symbolica replacements.
15///
16/// Keys are literal symbols, including names ending in underscores. Values may
17/// retain constants or symbols outside this map; this operation resolves only
18/// dependencies among its keys. It neither numerically evaluates nor expands
19/// the expressions. Cyclic or unresolved dependencies between keys are errors.
20pub fn resolve_scalar_bindings(
21 mut values: BTreeMap<Symbol, Atom>,
22) -> Result<BTreeMap<Symbol, Atom>, ModelError> {
23 for _ in 0..=values.len() {
24 let replacements = values
25 .iter()
26 .map(|(symbol, value)| {
27 Replacement::new(
28 Pattern::Literal(Atom::var(*symbol)),
29 Pattern::Literal(value.clone()),
30 )
31 })
32 .collect::<Vec<_>>();
33 let next = values
34 .iter()
35 .map(|(symbol, value)| (*symbol, value.replace_multiple(&replacements)))
36 .collect::<BTreeMap<_, _>>();
37 if next == values {
38 break;
39 }
40 values = next;
41 }
42 if values.values().any(|value| {
43 values
44 .keys()
45 .any(|symbol| value.contains(Atom::var(*symbol).as_view()))
46 }) {
47 return Err(ModelError::UnresolvedScalarBindings);
48 }
49 Ok(values)
50}
51
52impl Model {
53 /// Return exact scalar bindings for this model without changing it.
54 ///
55 /// The optional card is applied to a copy. External parameters and explicit
56 /// card values become exact complex rationals representing their binary64
57 /// values. Internal parameters retain their analytic definitions unless
58 /// explicitly supplied by the card; cached dependent values are never used
59 /// instead of those definitions. Couplings remain analytic until the named
60 /// dependencies are substituted, without floating-point recomputation.
61 /// Arbitrary-precision inputs can be supplied directly as atoms in
62 /// `overrides`. To keep a parameter for later numerical or Dual evaluation,
63 /// override it with a distinct free symbol outside the binding map; a
64 /// self-reference would instead be an unresolved dependency.
65 ///
66 /// Exact `overrides` take precedence over both model and card definitions
67 /// before closure. Additional scalar keys are allowed. The returned map has
68 /// no dependencies on its own keys, but may retain other symbols/functions;
69 /// it is not an evaluator for arbitrary UFO functions or form factors.
70 ///
71 /// Pass the restriction card explicitly even for a model to which it was
72 /// previously applied: the model does not retain internal-override history.
73 pub fn scalar_bindings(
74 &self,
75 card: Option<&ParameterCard>,
76 overrides: &BTreeMap<Symbol, Atom>,
77 ) -> Result<BTreeMap<Symbol, Atom>, ModelError> {
78 let mut updated;
79 let model = if let Some(card) = card {
80 updated = self.clone();
81 updated.apply_parameter_card(card)?;
82 &updated
83 } else {
84 self
85 };
86 let mut values = BTreeMap::new();
87 for parameter in model.parameters() {
88 let analytic = parameter.expression.as_ref().filter(|_| {
89 parameter.nature == ParameterNature::Internal
90 && !card.is_some_and(|card| card.contains_key(¶meter.name))
91 });
92 let value = if let Some(expression) = analytic {
93 expression.clone()
94 } else if let Some(value) = parameter.value {
95 let exact = |number| {
96 Rational::try_from(number).map_err(|_| ModelError::NonFiniteScalarBinding {
97 name: parameter.name.clone(),
98 })
99 };
100 Atom::num(exact(value.re)?) + Atom::num(exact(value.im)?) * Atom::i()
101 } else if let Some(expression) = ¶meter.expression {
102 expression.clone()
103 } else {
104 continue;
105 };
106 values.insert(symbol!(&format!("UFO::{}", parameter.name)), value);
107 }
108 for coupling in model.couplings() {
109 values.insert(
110 symbol!(&format!("UFO::{}", coupling.name)),
111 coupling.expression.clone(),
112 );
113 }
114 values.extend(
115 overrides
116 .iter()
117 .map(|(symbol, value)| (*symbol, value.clone())),
118 );
119 resolve_scalar_bindings(values)
120 }
121}
122
123#[cfg(test)]
124mod tests;