Skip to main content

gammalooprs/integrands/
mod.rs

1pub mod evaluation;
2pub mod process;
3
4use crate::integrands::evaluation::{EvaluationResult, RawBatchEvaluationResult};
5use crate::integrands::process::{EvaluationTarget, ProcessIntegrand};
6use crate::integrands::process::{amplitude, cross_section};
7use crate::model::Model;
8use crate::observables::{
9    ObservableAccumulatorBundle, ObservableFileFormat, ObservableSnapshotBundle,
10};
11use crate::settings::runtime::IntegratorSettings;
12use crate::utils::F;
13#[cfg(test)]
14use crate::{is_interrupted, settings::RuntimeSettings};
15
16use color_eyre::Result;
17use enum_dispatch::enum_dispatch;
18use spenso::algebra::complex::Complex;
19#[cfg(test)]
20use symbolica::numerical_integration::ContinuousGrid;
21use symbolica::numerical_integration::{Grid, Sample};
22
23#[enum_dispatch]
24pub trait HasIntegrand {
25    /// Constructs the continuous or discrete integration grid required by this integrand.
26    fn create_grid(&self) -> Grid<F<f64>>;
27
28    /// Returns the integrand name used in state inspection, logs, and status output.
29    fn name(&self) -> String;
30
31    /// Evaluates one weighted grid sample against the supplied model and numerical controls.
32    fn evaluate_sample(
33        &mut self,
34        sample: &Sample<F<f64>>,
35        model: &Model,
36        wgt: F<f64>,
37        iter: usize,
38        use_arb_prec: bool,
39        max_eval: Complex<F<f64>>,
40    ) -> Result<EvaluationResult>;
41
42    /// Returns the number of continuous sampling dimensions used by the integrand.
43    fn get_n_dim(&self) -> usize;
44
45    /// Returns integrator settings specialized for this integrand, or the defaults.
46    fn get_integrator_settings(&self) -> IntegratorSettings {
47        IntegratorSettings::default()
48    }
49
50    /// Merges iteration-local result state from another worker integrand.
51    // In case your integrand supports observable, then overload this function to combine the observables
52    fn merge_results<I: HasIntegrand>(&mut self, _other: &mut I, _iter: usize) {}
53
54    /// Finalizes or writes iteration-local result state after an integration iteration.
55    // In case your integrand supports observable, then overload this function to write the observables to file
56    fn update_results(&mut self, _iter: usize) {}
57}
58
59/// The only production integrand container. Sampling acceptance tests use
60/// [`ProcessIntegrand`] with a reference overlay, so no standalone unit-volume
61/// or profile integrand is kept as a second owner of parameterization logic.
62#[derive(Clone)]
63#[allow(clippy::large_enum_variant)]
64pub enum Integrand {
65    /// Generated amplitude or cross-section process integrand.
66    ProcessIntegrand(Box<ProcessIntegrand>),
67    #[cfg(test)]
68    TestProbe(TestProbeIntegrand),
69}
70
71impl Integrand {
72    pub fn evaluate_samples_raw(
73        &mut self,
74        samples: &[Sample<F<f64>>],
75        target: EvaluationTarget<'_>,
76        iter: usize,
77        use_arb_prec: bool,
78        stop_on_interrupt: bool,
79        max_eval: Complex<F<f64>>,
80    ) -> Result<RawBatchEvaluationResult> {
81        match self {
82            Integrand::ProcessIntegrand(integrand) => integrand.evaluate_samples_raw(
83                target,
84                samples,
85                iter,
86                use_arb_prec,
87                stop_on_interrupt,
88                max_eval,
89            ),
90            #[cfg(test)]
91            Integrand::TestProbe(_) => {
92                let EvaluationTarget::Physical(model) = target else {
93                    return Err(color_eyre::eyre::eyre!(
94                        "reference overlays require a generated process"
95                    ));
96                };
97                let mut results = Vec::with_capacity(samples.len());
98                for sample in samples {
99                    if stop_on_interrupt && is_interrupted() {
100                        break;
101                    }
102                    results.push(self.evaluate_sample(
103                        sample,
104                        model,
105                        sample.get_weight(),
106                        iter,
107                        use_arb_prec,
108                        max_eval,
109                    )?);
110                }
111                Ok(RawBatchEvaluationResult {
112                    statistics: evaluation::StatisticsCounter::from_evaluation_results(&results),
113                    samples: results,
114                })
115            }
116        }
117    }
118
119    #[allow(clippy::too_many_arguments)]
120    pub fn evaluate_samples_raw_with_estimate(
121        &mut self,
122        samples: &[Sample<F<f64>>],
123        target: EvaluationTarget<'_>,
124        iter: usize,
125        use_arb_prec: bool,
126        stop_on_interrupt: bool,
127        max_eval: Complex<F<f64>>,
128        integral_estimate: Option<(f64, f64)>,
129    ) -> Result<RawBatchEvaluationResult> {
130        match self {
131            Integrand::ProcessIntegrand(integrand) => integrand.evaluate_samples_raw_with_estimate(
132                target,
133                samples,
134                iter,
135                use_arb_prec,
136                stop_on_interrupt,
137                max_eval,
138                integral_estimate,
139            ),
140            #[cfg(test)]
141            Integrand::TestProbe(_) => self.evaluate_samples_raw(
142                samples,
143                target,
144                iter,
145                use_arb_prec,
146                stop_on_interrupt,
147                max_eval,
148            ),
149        }
150    }
151
152    pub fn process_evaluation_result(&mut self, result: &EvaluationResult) -> Result<()> {
153        match self {
154            Integrand::ProcessIntegrand(integrand) => integrand.process_evaluation_result(result),
155            #[cfg(test)]
156            Integrand::TestProbe(_) => Ok(()),
157        }
158    }
159
160    pub fn merge_runtime_results(&mut self, other: &mut Integrand) -> Result<()> {
161        match (self, other) {
162            (Integrand::ProcessIntegrand(lhs), Integrand::ProcessIntegrand(rhs)) => {
163                lhs.merge_event_processing_runtime(rhs)
164            }
165            #[cfg(test)]
166            _ => Ok(()),
167        }
168    }
169
170    pub fn update_runtime_results(&mut self, iter: usize) {
171        match self {
172            Integrand::ProcessIntegrand(integrand) => {
173                integrand.update_event_processing_runtime(iter)
174            }
175            #[cfg(test)]
176            Integrand::TestProbe(_) => {}
177        }
178    }
179
180    pub fn observable_accumulator_bundle(&self) -> Option<ObservableAccumulatorBundle> {
181        match self {
182            Integrand::ProcessIntegrand(integrand) => integrand.observable_accumulator_bundle(),
183            #[cfg(test)]
184            Integrand::TestProbe(_) => None,
185        }
186    }
187
188    pub fn has_observables(&self) -> bool {
189        match self {
190            Integrand::ProcessIntegrand(integrand) => integrand.has_observables(),
191            #[cfg(test)]
192            Integrand::TestProbe(_) => false,
193        }
194    }
195
196    pub fn observable_snapshot_bundle(&self) -> Option<ObservableSnapshotBundle> {
197        match self {
198            Integrand::ProcessIntegrand(integrand) => integrand.observable_snapshot_bundle(),
199            #[cfg(test)]
200            Integrand::TestProbe(_) => None,
201        }
202    }
203
204    pub fn write_observable_snapshots(
205        &self,
206        path: impl AsRef<std::path::Path>,
207        format: ObservableFileFormat,
208    ) -> Result<()> {
209        match self {
210            Integrand::ProcessIntegrand(integrand) => {
211                integrand.write_observable_snapshots(path, format)
212            }
213            #[cfg(test)]
214            Integrand::TestProbe(_) => Ok(()),
215        }
216    }
217}
218
219impl HasIntegrand for Integrand {
220    fn name(&self) -> String {
221        match self {
222            Integrand::ProcessIntegrand(i) => i.name(),
223            #[cfg(test)]
224            Integrand::TestProbe(integrand) => integrand.name(),
225        }
226    }
227
228    fn create_grid(&self) -> Grid<F<f64>> {
229        match self {
230            Integrand::ProcessIntegrand(integrand) => integrand.create_grid(),
231            #[cfg(test)]
232            Integrand::TestProbe(integrand) => integrand.create_grid(),
233        }
234    }
235
236    fn evaluate_sample(
237        &mut self,
238        sample: &Sample<F<f64>>,
239        model: &Model,
240        wgt: F<f64>,
241        iter: usize,
242        use_arb_prec: bool,
243        max_eval: Complex<F<f64>>,
244    ) -> Result<EvaluationResult> {
245        match self {
246            Integrand::ProcessIntegrand(integrand) => {
247                integrand.evaluate_sample(sample, model, wgt, iter, use_arb_prec, max_eval)
248            }
249            #[cfg(test)]
250            Integrand::TestProbe(integrand) => {
251                integrand.evaluate_sample(sample, model, wgt, iter, use_arb_prec, max_eval)
252            }
253        }
254    }
255
256    fn get_n_dim(&self) -> usize {
257        match self {
258            Integrand::ProcessIntegrand(integrand) => integrand.get_n_dim(),
259            #[cfg(test)]
260            Integrand::TestProbe(integrand) => integrand.get_n_dim(),
261        }
262    }
263
264    fn get_integrator_settings(&self) -> IntegratorSettings {
265        match self {
266            Integrand::ProcessIntegrand(integrand) => integrand.get_integrator_settings(),
267            #[cfg(test)]
268            Integrand::TestProbe(integrand) => integrand.get_integrator_settings(),
269        }
270    }
271}
272
273/// Minimal test-only integrand used for exercising the integration state and
274/// monitoring machinery. It intentionally has no standalone production owner;
275/// process-level acceptance tests cover actual sampling and Jacobians.
276#[cfg(test)]
277#[derive(Clone)]
278pub struct TestProbeIntegrand {
279    settings: RuntimeSettings,
280    n_dim: usize,
281}
282
283#[cfg(test)]
284impl TestProbeIntegrand {
285    pub(crate) fn new(settings: RuntimeSettings, n_dim: usize) -> Self {
286        Self { settings, n_dim }
287    }
288}
289
290#[cfg(test)]
291impl HasIntegrand for TestProbeIntegrand {
292    fn create_grid(&self) -> Grid<F<f64>> {
293        Grid::Continuous(
294            ContinuousGrid::new(
295                self.n_dim,
296                self.settings.integrator.n_bins,
297                self.settings.integrator.min_samples_for_update,
298                self.settings.integrator.bin_number_evolution.clone(),
299                self.settings.integrator.train_on_avg,
300            )
301            .expect("test-probe integration requires valid continuous-grid settings"),
302        )
303    }
304
305    fn name(&self) -> String {
306        "TestProbeIntegrand".to_string()
307    }
308
309    fn evaluate_sample(
310        &mut self,
311        _sample: &Sample<F<f64>>,
312        _model: &Model,
313        wgt: F<f64>,
314        _iter: usize,
315        _use_arb_prec: bool,
316        _max_eval: Complex<F<f64>>,
317    ) -> Result<EvaluationResult> {
318        let mut result = EvaluationResult::zero();
319        result.integrand_result = Complex::new_re(F(1.0));
320        result.parameterization_jacobian = Some(F(1.0));
321        result.integrator_weight = wgt;
322        Ok(result)
323    }
324
325    fn get_n_dim(&self) -> usize {
326        self.n_dim
327    }
328}