Skip to main content

gammalooprs/processes/
mod.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    fs,
4    path::Path,
5    sync::Arc,
6};
7
8// use bincode::{Decode, Encode};
9use bincode_trait_derive::{Decode, Encode};
10use color_eyre::Result;
11use eyre::{Context, eyre};
12use rayon::ThreadPool;
13use schemars::JsonSchema;
14use symbolica::evaluate::OptimizationSettings;
15use tracing::debug;
16
17use crate::{
18    GammaLoopContext, GammaLoopContextContainer,
19    settings::{GlobalSettings, runtime::LockedRuntimeSettings},
20    utils::serde_utils::{IsDefault, is_false, is_true, is_usize, show_defaults_helper},
21    uv::export::UVForestExportSettings,
22};
23use serde::{Deserialize, Serialize};
24
25use crate::graph::Graph;
26use crate::integrands::process::ProcessIntegrand;
27use crate::model::Model;
28
29mod generation_report;
30pub use generation_report::{
31    EvaluatorBuildTimings, GeneratedGraphKey, GeneratedGraphReport, GenerationTimings,
32    GraphGenerationStats, NamedGraphGenerationReport, RepresentationGenerationStats,
33    merge_generated_graph_reports,
34};
35mod generation_progress;
36pub use generation_progress::{
37    GenerationProcessKind, GenerationProgressMode, GenerationProgressModeGuard,
38    GenerationProgressObserver, GenerationProgressObserverGuard, GenerationProgressPhase,
39    begin_phase, cut_finished, detailed_progress_enabled, detailed_progress_message,
40    enter_detailed_progress_span, enter_progress_context,
41};
42mod selection;
43pub use selection::{
44    CycleSignature, GraphGroupSelectionMode, GraphGroupSelectionPlan, GraphGroupSelectionReport,
45    GraphGroupSelectionSpec, GraphSelectionSignatureInventory, ParticleSignature,
46    RaisedCutSignatureInventory, RaisedPropagatorScope, RaisedPropagatorSignature,
47    SelectionPolarity, VertexSignature,
48};
49pub(crate) use selection::{GraphCutSelectionSubject, GraphSelectionSubject};
50
51#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
52#[derive(
53    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
54)]
55#[serde(rename_all = "snake_case")]
56pub enum TensorNetworkContractionOrder {
57    SparseAtomAware,
58    AtomAware,
59    ResultRankOnly,
60    EntryAware,
61    #[default]
62    IntermediateCost,
63}
64
65#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
66#[derive(Debug, Clone, Copy, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
67pub enum ExecutionMode {
68    Sequential,
69    Parallel,
70    SequentialRef,
71    SequentialExtract,
72}
73
74#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
75#[derive(Debug, Clone, Copy, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
76pub enum ContractionMode {
77    SmallestDegree,
78    MinResultRank,
79}
80#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
81#[derive(Debug, Clone, Copy, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
82pub struct EvaluatorSettings {
83    /// Perform symbolic tensor and scalar algebra before lowering to an evaluator.
84    #[serde(default, skip_serializing_if = "is_false")]
85    pub do_algebra: bool,
86    /// Re-optimize orientation expressions iteratively while building the evaluator.
87    #[serde(
88        default = "evaluator_default_iterative_orientation_optimization",
89        skip_serializing_if = "is_true"
90    )]
91    pub iterative_orientation_optimization: bool,
92    /// Build one evaluator for the sum of all contributions instead of separate evaluators.
93    #[serde(default, skip_serializing_if = "is_false")]
94    pub summed: bool,
95    /// Sum all orientations, retaining each selected orientation as a separate
96    /// Symbolica function-map alias instead of merging them into one expression.
97    #[serde(default, skip_serializing_if = "is_false")]
98    pub summed_function_map: bool,
99    /// Compile the lowered evaluator using the configured generation compilation backend.
100    #[serde(default, skip_serializing_if = "is_false")]
101    pub compile: bool,
102    /// Retain the intermediate Symbolica atom alongside the executable evaluator.
103    #[serde(default, skip_serializing_if = "is_false")]
104    pub store_atom: bool,
105    /// Apply function-map replacements before numerical lowering.
106    #[serde(default, skip_serializing_if = "is_false")]
107    pub do_fn_map_replacements: bool,
108    /// Inline generated numerator functions instead of retaining shared evaluator bodies.
109    #[serde(
110        default = "evaluator_default_inline_numerator_functions",
111        skip_serializing_if = "is_true"
112    )]
113    pub inline_numerator_functions: bool,
114    /// Translate compatible symbolic expressions directly into Spenso networks.
115    #[serde(
116        default = "evaluator_default_direct_translation",
117        skip_serializing_if = "is_true"
118    )]
119    pub direct_translation: bool,
120    /// Number of Horner-scheme optimization passes applied to scalar expressions.
121    #[serde(
122        default = "evaluator_default_horner_iterations",
123        skip_serializing_if = "is_usize::<1>"
124    )]
125    pub horner_iterations: usize,
126    /// Worker threads used while constructing one evaluator.
127    #[serde(
128        default = "evaluator_default_n_cores",
129        skip_serializing_if = "is_usize::<1>"
130    )]
131    pub n_cores: usize,
132    /// Optional number of common-pair-elimination optimization passes.
133    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
134    pub cpe_iterations: Option<usize>,
135    /// Optimization stage at which evaluator construction aborts for diagnostic isolation.
136    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
137    pub abort_level: usize,
138
139    /// Maximum variable count for attempting a Horner-scheme optimization.
140    #[serde(
141        default = "evaluator_default_max_horner_scheme_variables",
142        skip_serializing_if = "is_usize::<500>"
143    )]
144    pub max_horner_scheme_variables: usize,
145
146    /// Maximum cached candidate pairs during common-pair elimination.
147    #[serde(
148        default = "evaluator_default_max_common_pair_cache_entries",
149        skip_serializing_if = "is_usize::<1000000>"
150    )]
151    pub max_common_pair_cache_entries: usize,
152
153    /// Maximum expression-tree distance considered during common-pair elimination.
154    #[serde(
155        default = "evaluator_default_max_common_pair_distance",
156        skip_serializing_if = "is_usize::<1000>"
157    )]
158    pub max_common_pair_distance: usize,
159    /// Heuristic used to order tensor-network contractions.
160    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
161    pub tensor_network_contraction_order: TensorNetworkContractionOrder,
162    /// Emit detailed evaluator-construction diagnostics.
163    #[serde(default, skip_serializing_if = "is_false")]
164    pub verbose: bool,
165
166    /// Spenso execution and contraction modes used by the lowered tensor network.
167    #[serde(
168        default = "evaluator_default_spenso_execution_mode",
169        skip_serializing_if = "is_default_spenso_execution_mode"
170    )]
171    pub spenso_execution_mode: (ExecutionMode, ContractionMode),
172}
173
174const fn evaluator_default_iterative_orientation_optimization() -> bool {
175    true
176}
177
178const fn evaluator_default_direct_translation() -> bool {
179    true
180}
181
182const fn evaluator_default_inline_numerator_functions() -> bool {
183    true
184}
185
186const fn evaluator_default_horner_iterations() -> usize {
187    1
188}
189
190const fn evaluator_default_n_cores() -> usize {
191    1
192}
193
194const fn evaluator_default_max_horner_scheme_variables() -> usize {
195    500
196}
197
198const fn evaluator_default_max_common_pair_cache_entries() -> usize {
199    1_000_000
200}
201
202const fn evaluator_default_max_common_pair_distance() -> usize {
203    1000
204}
205
206const fn evaluator_default_spenso_execution_mode() -> (ExecutionMode, ContractionMode) {
207    (ExecutionMode::Sequential, ContractionMode::MinResultRank)
208}
209
210fn is_default_spenso_execution_mode(mode: &(ExecutionMode, ContractionMode)) -> bool {
211    show_defaults_helper(mode == &evaluator_default_spenso_execution_mode())
212}
213
214impl Default for EvaluatorSettings {
215    fn default() -> Self {
216        Self {
217            iterative_orientation_optimization:
218                evaluator_default_iterative_orientation_optimization(),
219            summed: false,
220            do_algebra: false,
221            summed_function_map: false,
222            direct_translation: evaluator_default_direct_translation(),
223            compile: false,
224            do_fn_map_replacements: false,
225            inline_numerator_functions: evaluator_default_inline_numerator_functions(),
226            store_atom: false,
227            horner_iterations: evaluator_default_horner_iterations(),
228            n_cores: evaluator_default_n_cores(),
229            cpe_iterations: None,
230            abort_level: 0,
231            max_horner_scheme_variables: evaluator_default_max_horner_scheme_variables(),
232            max_common_pair_cache_entries: evaluator_default_max_common_pair_cache_entries(),
233            max_common_pair_distance: evaluator_default_max_common_pair_distance(),
234            tensor_network_contraction_order: TensorNetworkContractionOrder::default(),
235            verbose: false,
236            spenso_execution_mode: evaluator_default_spenso_execution_mode(),
237        }
238    }
239}
240
241impl EvaluatorSettings {
242    pub fn optimization_settings(&self) -> OptimizationSettings {
243        OptimizationSettings::new()
244            .horner_iterations(self.horner_iterations)
245            .cores(self.n_cores)
246            .cpe_iterations(self.cpe_iterations)
247            .abort_check(Some(Box::new(
248                crate::is_interrupt_requested as fn() -> bool,
249            )))
250            .abort_level(self.abort_level)
251            .max_horner_scheme_variables(self.max_horner_scheme_variables)
252            .max_common_pair_cache_entries(self.max_common_pair_cache_entries)
253            .max_common_pair_distance(self.max_common_pair_distance)
254            .verbose(self.verbose)
255            .direct_translation(self.direct_translation)
256    }
257}
258
259#[derive(Clone, Encode, Decode)]
260#[trait_decode(trait = GammaLoopContext)]
261pub struct ProcessList {
262    // pub amplitude_process: Vec<Process<Amplitude>>
263    // pub cross_section_process: Vec<Process<CrossSection>>
264    pub processes: Vec<Process>,
265}
266
267/// Restricts which saved processes and integrands are loaded into a process list.
268///
269/// An unqualified integrand selector applies to every process containing an
270/// integrand with that name, while a qualified selector applies only to its
271/// named process. Process selectors take precedence and load every integrand
272/// in the selected process.
273#[derive(Debug, Clone, Default, PartialEq, Eq)]
274pub struct ProcessLoadSelection {
275    pub process_names: BTreeSet<String>,
276    pub integrand_selectors: Vec<ProcessLoadIntegrandSelector>,
277}
278
279#[derive(Debug, Clone, PartialEq, Eq)]
280pub enum ProcessLoadIntegrandSelector {
281    Name(String),
282    Qualified {
283        process_name: String,
284        integrand_name: String,
285    },
286}
287
288impl ProcessLoadSelection {
289    pub fn is_unrestricted(&self) -> bool {
290        self.process_names.is_empty() && self.integrand_selectors.is_empty()
291    }
292
293    pub fn selected_integrand_names<'a, I>(
294        &self,
295        process_name: &str,
296        available_names: I,
297    ) -> BTreeSet<String>
298    where
299        I: IntoIterator<Item = &'a str>,
300    {
301        let available_names = available_names.into_iter();
302        if self.process_names.contains(process_name) {
303            return available_names.map(str::to_string).collect();
304        }
305
306        available_names
307            .filter(|integrand_name| {
308                self.integrand_selectors
309                    .iter()
310                    .any(|selector| match selector {
311                        ProcessLoadIntegrandSelector::Name(name) => name == *integrand_name,
312                        ProcessLoadIntegrandSelector::Qualified {
313                            process_name: selected_process,
314                            integrand_name: selected_integrand,
315                        } => {
316                            selected_process == process_name
317                                && selected_integrand == *integrand_name
318                        }
319                    })
320            })
321            .map(str::to_string)
322            .collect()
323    }
324}
325
326#[cfg(test)]
327mod process_load_selection_tests {
328    use super::{ProcessLoadIntegrandSelector, ProcessLoadSelection};
329    use std::collections::BTreeSet;
330
331    #[test]
332    fn process_and_integrand_selectors_are_unioned() {
333        let selection = ProcessLoadSelection {
334            process_names: BTreeSet::from(["all".to_string()]),
335            integrand_selectors: vec![
336                ProcessLoadIntegrandSelector::Name("shared".to_string()),
337                ProcessLoadIntegrandSelector::Qualified {
338                    process_name: "one".to_string(),
339                    integrand_name: "specific".to_string(),
340                },
341            ],
342        };
343
344        assert_eq!(
345            selection.selected_integrand_names("all", ["a", "b"]),
346            BTreeSet::from(["a".to_string(), "b".to_string()])
347        );
348        assert_eq!(
349            selection.selected_integrand_names("one", ["shared", "specific", "other"]),
350            BTreeSet::from(["shared".to_string(), "specific".to_string()])
351        );
352        assert_eq!(
353            selection.selected_integrand_names("two", ["shared", "specific"]),
354            BTreeSet::from(["shared".to_string()])
355        );
356    }
357}
358
359fn validate_process_load_selection(
360    processes_root: &Path,
361    selection: &ProcessLoadSelection,
362) -> Result<()> {
363    let mut available: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
364    for (directory, binary, kind) in [
365        ("amplitudes", "amp.bin", "amplitude"),
366        ("cross_sections", "cs.bin", "cross section"),
367    ] {
368        let root = processes_root.join(directory);
369        if !root.exists() {
370            continue;
371        }
372        for entry in
373            fs::read_dir(&root).with_context(|| format!("Error reading {}", root.display()))?
374        {
375            let entry = entry?;
376            if !entry.file_type()?.is_dir() {
377                continue;
378            }
379            let Some(process_name) = entry.file_name().to_str().map(str::to_owned) else {
380                continue;
381            };
382            let child_dirs = process::saved_child_dirs(&entry.path(), binary, kind)?;
383            let names = available.entry(process_name).or_default();
384            names.extend(child_dirs.into_iter().filter_map(|path| {
385                path.file_name()
386                    .and_then(|name| name.to_str())
387                    .map(str::to_owned)
388            }));
389        }
390    }
391
392    let mut errors = Vec::new();
393
394    for process_name in &selection.process_names {
395        if !available.contains_key(process_name) {
396            errors.push(format!("process '{process_name}' was not found"));
397        }
398    }
399    for selector in &selection.integrand_selectors {
400        match selector {
401            ProcessLoadIntegrandSelector::Name(integrand_name) => {
402                if !available.values().any(|names| names.contains(integrand_name)) {
403                    errors.push(format!("integrand '{integrand_name}' was not found"));
404                }
405            }
406            ProcessLoadIntegrandSelector::Qualified {
407                process_name,
408                integrand_name,
409            } => match available.get(process_name) {
410                None => errors.push(format!(
411                    "process '{process_name}' in selector '{process_name}@{integrand_name}' was not found"
412                )),
413                Some(names) if !names.contains(integrand_name) => errors.push(format!(
414                    "integrand '{integrand_name}' was not found in process '{process_name}'"
415                )),
416                Some(_) => {}
417            },
418        }
419    }
420
421    if errors.is_empty() {
422        return Ok(());
423    }
424
425    Err(eyre!(
426        "Cannot load the requested process/integrand selection: {}. Available integrands by process: {:?}",
427        errors.join("; "),
428        available,
429    ))
430}
431
432/// Controls which graph details and algebraic transformations are included in DOT exports.
433#[derive(Serialize, Deserialize, Debug, Clone)]
434#[cfg_attr(feature = "python-stubs", pyo3_stub_gen::derive::gen_stub_pyclass)]
435#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
436pub struct DotExportSettings {
437    // pub root_folder: PathBuf,
438    /// Write all diagrams of an integrand to one file during filesystem export.
439    pub combine_diagrams: bool,
440    /// Request UV counterterm graph output; currently retained for compatibility.
441    pub with_uv: bool,
442    /// Add the complete symbolic numerator as the graph-level `full_num` field.
443    pub output_full_numerator: bool,
444    /// Split cross-section graphs by distinct initial-state assignments.
445    pub split_xs_by_initial_states: bool,
446    /// Simplify gamma-matrix algebra in the full numerator before formatting it.
447    pub do_gamma_algebra: bool,
448    /// Simplify color algebra in the full numerator before formatting it.
449    pub do_color_algebra: bool,
450    #[serde(default, skip_serializing_if = "is_false")]
451    /// Include vertex and edge fields whose values GammaLoop generated automatically.
452    pub include_autogenerated_fields: bool,
453}
454
455#[derive(Serialize, Deserialize, Debug, Clone)]
456#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
457pub struct StandaloneExportSettings {
458    #[serde(default)]
459    pub mode: StandaloneExportMode,
460    #[serde(default)]
461    pub format: StandaloneDataFormat,
462    #[serde(default)]
463    pub precision: StandaloneNumericTarget,
464}
465
466#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
467#[derive(
468    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default, Encode, Decode, JsonSchema,
469)]
470#[serde(rename_all = "snake_case")]
471pub enum StandaloneExportMode {
472    #[default]
473    Rust,
474    Python,
475}
476
477#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
478#[derive(
479    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default, Encode, Decode, JsonSchema,
480)]
481#[serde(rename_all = "snake_case")]
482pub enum StandaloneDataFormat {
483    #[default]
484    Binary,
485    Json,
486}
487
488#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
489#[derive(
490    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default, Encode, Decode, JsonSchema,
491)]
492#[serde(rename_all = "snake_case")]
493pub enum StandaloneNumericTarget {
494    #[default]
495    Double,
496    Quad,
497    Arb,
498}
499
500#[cfg(feature = "python")]
501#[cfg_attr(feature = "python-stubs", pyo3_stub_gen::derive::gen_stub_pymethods)]
502#[cfg_attr(feature = "python", pyo3::pymethods)]
503impl DotExportSettings {
504    /// Construct DOT export settings with GammaLoop's defaults.
505    #[new]
506    fn new() -> Self {
507        DotExportSettings::default()
508    }
509}
510
511impl Default for DotExportSettings {
512    fn default() -> Self {
513        Self {
514            // root_folder: PathBuf::from("."),
515            split_xs_by_initial_states: false,
516            output_full_numerator: false,
517            do_gamma_algebra: false,
518            do_color_algebra: true,
519            combine_diagrams: false,
520            with_uv: false,
521            include_autogenerated_fields: false,
522        }
523    }
524}
525
526impl Default for StandaloneExportSettings {
527    fn default() -> Self {
528        Self {
529            format: StandaloneDataFormat::Binary,
530            mode: StandaloneExportMode::Rust,
531            precision: StandaloneNumericTarget::Double,
532        }
533    }
534}
535
536impl Default for ProcessList {
537    fn default() -> Self {
538        Self::new()
539    }
540}
541
542// Python Api
543impl ProcessList {
544    /// Generates a new empty process list
545    pub fn new() -> Self {
546        ProcessList { processes: vec![] }
547    }
548
549    pub fn warm_up_all_processes(&mut self, model: &Model) -> Result<()> {
550        for process in &mut self.processes.iter_mut() {
551            process.warm_up(model)?;
552        }
553
554        Ok(())
555    }
556
557    pub fn load(path: impl AsRef<Path>, context: GammaLoopContextContainer) -> Result<Self> {
558        Self::load_with_selection(path, context, None)
559    }
560
561    pub fn load_with_selection(
562        path: impl AsRef<Path>,
563        context: GammaLoopContextContainer,
564        selection: Option<&ProcessLoadSelection>,
565    ) -> Result<Self> {
566        let mut process_list = Self::new();
567        let selection = selection.filter(|selection| !selection.is_unrestricted());
568
569        let path = path.as_ref().join("processes");
570        if let Some(selection) = selection {
571            validate_process_load_selection(&path, selection)?;
572        }
573        let amplitudes_path = path.join("amplitudes");
574        if amplitudes_path.exists() {
575            debug!("Looking for amplitudes in {}", amplitudes_path.display());
576
577            for entry in fs::read_dir(amplitudes_path).context("Error reading dir")? {
578                let Ok(entry) = entry else {
579                    debug!("Skipping invalid entry");
580
581                    continue;
582                };
583                let path = entry.path();
584                let process_name = path.file_name().and_then(|name| name.to_str());
585                let process_selected = selection.is_some_and(|selection| {
586                    process_name.is_some_and(|name| selection.process_names.contains(name))
587                });
588                let selected_integrands = match (selection, process_name) {
589                    (Some(selection), Some(process_name)) => {
590                        let available = process::saved_child_dirs(&path, "amp.bin", "amplitude")?;
591                        Some(
592                            selection.selected_integrand_names(
593                                process_name,
594                                available.iter().filter_map(|path| {
595                                    path.file_name().and_then(|name| name.to_str())
596                                }),
597                            ),
598                        )
599                    }
600                    _ => None,
601                };
602                if selected_integrands.as_ref().is_some_and(BTreeSet::is_empty) && !process_selected
603                {
604                    continue;
605                }
606                let process = Process::load_amplitude(path, context, selected_integrands.as_ref())
607                    .context("Error loading amplitude")?;
608                process_list.processes.push(process);
609            }
610        }
611
612        let cross_sections_path = path.join("cross_sections");
613        if cross_sections_path.exists() {
614            debug!(
615                "Looking for cross sections in {}",
616                cross_sections_path.display()
617            );
618
619            for entry in fs::read_dir(cross_sections_path)? {
620                let entry = entry?;
621                let path = entry.path();
622                let process_name = path.file_name().and_then(|name| name.to_str());
623                let process_selected = selection.is_some_and(|selection| {
624                    process_name.is_some_and(|name| selection.process_names.contains(name))
625                });
626                let selected_integrands =
627                    match (selection, process_name) {
628                        (Some(selection), Some(process_name)) => {
629                            let available =
630                                process::saved_child_dirs(&path, "cs.bin", "cross section")?;
631                            Some(selection.selected_integrand_names(
632                                process_name,
633                                available.iter().filter_map(|path| {
634                                    path.file_name().and_then(|name| name.to_str())
635                                }),
636                            ))
637                        }
638                        _ => None,
639                    };
640                if selected_integrands.as_ref().is_some_and(BTreeSet::is_empty) && !process_selected
641                {
642                    continue;
643                }
644                let process =
645                    Process::load_cross_section(path, context, selected_integrands.as_ref())?;
646                process_list.processes.push(process);
647            }
648        }
649        process_list
650            .processes
651            .sort_by_key(|p| p.definition.process_id);
652
653        if selection.is_some() {
654            for (process_id, process) in process_list.processes.iter_mut().enumerate() {
655                process.definition.process_id = process_id;
656            }
657        }
658
659        Ok(process_list)
660    }
661
662    pub fn save(&mut self, folder: impl AsRef<Path>, override_existing: bool) -> Result<()> {
663        let path = folder.as_ref().join("processes");
664
665        let r = fs::create_dir_all(&path);
666        if !override_existing {
667            r?;
668        }
669
670        for p in self.processes.iter_mut() {
671            p.save(&path, override_existing)?;
672        }
673
674        Ok(())
675    }
676
677    pub fn compile(
678        &mut self,
679        folder: impl AsRef<Path>,
680        override_existing: bool,
681        process_id: Option<usize>,
682        integrand_name: Option<String>,
683        thread_pool: &ThreadPool,
684    ) -> Result<Vec<GeneratedGraphReport>> {
685        let path = folder.as_ref().join("processes");
686
687        let r = fs::create_dir_all(&path);
688        if !override_existing {
689            r?;
690        }
691
692        let mut reports = Vec::new();
693        for p in self.processes.iter_mut() {
694            if let Some(id) = process_id
695                && p.definition.process_id != id
696            {
697                continue;
698            }
699            reports.extend(p.compile(
700                &path,
701                override_existing,
702                integrand_name.clone(),
703                thread_pool,
704            )?);
705        }
706
707        Ok(reports)
708    }
709
710    pub fn activate_loaded_integrand_backends(
711        &mut self,
712        allow_symjit_fallback: bool,
713    ) -> Result<()> {
714        for process in &mut self.processes {
715            process.activate_loaded_integrand_backends(allow_symjit_fallback)?;
716        }
717        Ok(())
718    }
719
720    pub fn get_integrand(
721        &self,
722        process_id: usize,
723        integrand_name: impl AsRef<str>,
724    ) -> Result<crate::processes::process::ResolvedIntegrandRef<'_>> {
725        let process = &self.processes[process_id];
726        process.get_integrand(integrand_name)
727    }
728
729    pub fn get_integrand_mut(
730        &mut self,
731        process_id: usize,
732        integrand_name: impl AsRef<str>,
733    ) -> Result<&mut crate::integrands::process::ProcessIntegrand> {
734        let process = &mut self.processes[process_id];
735        process.get_integrand_mut(integrand_name)
736    }
737
738    pub fn export_dot(&self, path: impl AsRef<Path>, settings: &DotExportSettings) -> Result<()> {
739        let path = path.as_ref().join("processes");
740        fs::create_dir_all(&path)?;
741
742        for p in self.processes.iter() {
743            p.export_dot(&path, settings)?;
744        }
745        Ok(())
746    }
747
748    pub fn export_uv_forests(
749        &self,
750        model: &Model,
751        path: impl AsRef<Path>,
752        process_id: usize,
753        integrand_name: &str,
754        graph_ids: &[usize],
755        settings: &UVForestExportSettings,
756    ) -> Result<()> {
757        let path = path.as_ref().join("processes");
758        fs::create_dir_all(&path)?;
759        let process = self.processes.get(process_id).ok_or_else(|| {
760            eyre!(
761                "Process id {} is out of range; there are {} processes",
762                process_id,
763                self.processes.len()
764            )
765        })?;
766        process.export_uv_forests(model, &path, integrand_name, graph_ids, settings)
767    }
768
769    pub fn export_standalone(
770        &self,
771        path: impl AsRef<Path>,
772        settings: &StandaloneExportSettings,
773    ) -> Result<()> {
774        let path = path.as_ref().join("processes");
775        fs::create_dir_all(&path)?;
776
777        for p in self.processes.iter() {
778            p.export_standalone(&path, settings)?;
779        }
780        Ok(())
781    }
782
783    pub fn add_process(&mut self, process: Process) {
784        self.processes.push(process);
785    }
786
787    /// Every graph held by `process`: each retained source graph with its
788    /// derived threshold topology and multi-channeling setup, and every graph
789    /// of the generated integrands (terms and their multi-channeling setups).
790    pub fn process_graphs(process: &Process) -> Vec<&Graph> {
791        match &process.collection {
792            ProcessCollection::Amplitudes(amplitudes) => amplitudes
793                .values()
794                .flat_map(|amplitude| {
795                    amplitude
796                        .graphs
797                        .iter()
798                        .flat_map(AmplitudeGraph::graphs)
799                        .chain(
800                            amplitude
801                                .integrand
802                                .iter()
803                                .flat_map(ProcessIntegrand::graphs),
804                        )
805                })
806                .collect(),
807            ProcessCollection::CrossSections(cross_sections) => cross_sections
808                .values()
809                .flat_map(|cross_section| {
810                    cross_section
811                        .supergraphs
812                        .iter()
813                        .flat_map(CrossSectionGraph::graphs)
814                        .chain(
815                            cross_section
816                                .integrand
817                                .iter()
818                                .flat_map(ProcessIntegrand::graphs),
819                        )
820                })
821                .collect(),
822        }
823    }
824
825    /// The model handle shared by the held graphs, if any graph is held.
826    pub fn shared_graph_model(&self) -> Option<&Arc<Model>> {
827        self.processes.iter().find_map(|process| {
828            Self::process_graphs(process)
829                .into_iter()
830                .next()
831                .map(|graph| &graph.model)
832        })
833    }
834
835    /// Check that `model` resolves the typed identifiers of every held graph
836    /// (see [`Self::process_graphs`]) to the same records. This is an identity
837    /// check only; numerical requirements are the caller's.
838    pub fn ensure_graphs_bound_to(&self, model: &Model) -> Result<()> {
839        for process in &self.processes {
840            Self::process_graphs(process)
841                .into_iter()
842                .try_for_each(|graph| graph.ensure_bound_to(model))
843                .wrap_err_with(|| {
844                    format!(
845                        "process '{}' cannot use model '{}'; remove it with `remove processes -p \
846                         name:{}` or start a new state, then regenerate it with the new model",
847                        process.definition.folder_name,
848                        model.name(),
849                        process.definition.folder_name,
850                    )
851                })?;
852        }
853        Ok(())
854    }
855
856    /// Rebind every held graph (see [`Self::process_graphs`]) to `model`,
857    /// validated with [`Self::ensure_graphs_bound_to`], and invalidate the
858    /// runtime caches built from the previous model so that the next warm-up
859    /// uses the new values.
860    pub fn rebind_graph_models(&mut self, model: &Arc<Model>) {
861        for process in &mut self.processes {
862            match &mut process.collection {
863                ProcessCollection::Amplitudes(amplitudes) => {
864                    for amplitude in amplitudes.values_mut() {
865                        for graph in &mut amplitude.graphs {
866                            graph.rebind_model(model);
867                        }
868                        if let Some(integrand) = &mut amplitude.integrand {
869                            integrand.rebind_model(model);
870                        }
871                    }
872                }
873                ProcessCollection::CrossSections(cross_sections) => {
874                    for cross_section in cross_sections.values_mut() {
875                        for graph in &mut cross_section.supergraphs {
876                            graph.rebind_model(model);
877                        }
878                        if let Some(integrand) = &mut cross_section.integrand {
879                            integrand.rebind_model(model);
880                        }
881                    }
882                }
883            }
884        }
885    }
886
887    ///preprocesses the process list according to the settings
888    pub fn preprocess(
889        &mut self,
890        model: &Model,
891        settings: &GlobalSettings,
892        locked_runtime_settings: &LockedRuntimeSettings,
893        thread_pool: &ThreadPool,
894    ) -> Result<Vec<GeneratedGraphReport>> {
895        // Reject unsupported settings before any process changes its graphs or history.
896        for process in &self.processes {
897            settings
898                .generation
899                .validate_for_process(process.definition.generation_type)?;
900        }
901        let mut reports = Vec::new();
902        for process in self.processes.iter_mut() {
903            reports.extend(process.preprocess(
904                model,
905                settings,
906                locked_runtime_settings,
907                thread_pool,
908            )?);
909        }
910        Ok(reports)
911    }
912
913    pub fn generate_integrands(
914        &mut self,
915        model: &Model,
916        global_settings: &GlobalSettings,
917        runtime_default: LockedRuntimeSettings,
918        thread_pool: &ThreadPool,
919    ) -> Result<Vec<GeneratedGraphReport>> {
920        let mut reports = Vec::new();
921        for process in &mut self.processes {
922            reports.extend(process.generate_integrands(
923                model,
924                global_settings,
925                runtime_default,
926                thread_pool,
927            )?);
928        }
929        Ok(reports)
930    }
931
932    pub fn find_process(&self, process_id: Option<usize>) -> Result<usize> {
933        if let Some(id) = process_id {
934            if id >= self.processes.len() {
935                return Err(color_eyre::eyre::eyre!(
936                    "Invalid process id {}. Number of processes: {}",
937                    id,
938                    self.processes.len()
939                ));
940            }
941            Ok(id)
942        } else if self.processes.is_empty() {
943            Err(color_eyre::eyre::eyre!("No processes generated yet."))
944        } else if self.processes.len() > 1 {
945            Err(color_eyre::eyre::eyre!(
946                "There are {} processes available. Please specify a process.",
947                self.processes.len()
948            ))
949        } else {
950            Ok(0)
951        }
952    }
953
954    pub fn find_integrand(
955        &self,
956        process_id: Option<usize>,
957        integrand_name: Option<&String>,
958    ) -> Result<(usize, String)> {
959        let p_id = self.find_process(process_id)?;
960        let integrand_name = self.processes[p_id]
961            .collection
962            .find_integrand(integrand_name.cloned())?;
963        Ok((p_id, integrand_name))
964    }
965}
966
967pub mod process;
968pub use process::*;
969pub mod amplitude;
970pub use amplitude::*;
971pub mod cross_section;
972pub use cross_section::*;
973pub mod threshold_counterterms;
974pub use threshold_counterterms::*;
975
976#[cfg(test)]
977mod no_directive_equivalence_tests;
978#[cfg(test)]
979mod raised_cross_section_tests;
980
981#[cfg(test)]
982mod tests {
983    use std::sync::Arc;
984
985    use symbolica::state::State;
986
987    use crate::{
988        GammaLoopContextContainer,
989        graph::Graph,
990        initialisation::test_initialise,
991        settings::{
992            RuntimeSettings,
993            global::{
994                CompilationMode, CompilationOptimizationLevel, GammaloopCompileOptions,
995                GenerationSettings, TropicalSubgraphTableSettings,
996            },
997            runtime::LockedRuntimeSettings,
998        },
999        utils::load_generic_model,
1000    };
1001
1002    use super::{AmplitudeGraph, EvaluatorSettings};
1003
1004    #[test]
1005    fn numerator_inlining_defaults_and_explicit_opt_out_round_trip() {
1006        use crate::utils::serde_utils::ShowDefaultsGuard;
1007
1008        assert!(EvaluatorSettings::default().inline_numerator_functions);
1009        for input in ["", "n_cores = 2"] {
1010            let settings: EvaluatorSettings = toml::from_str(input).unwrap();
1011            assert!(settings.inline_numerator_functions);
1012        }
1013
1014        {
1015            let _guard = ShowDefaultsGuard::new(false);
1016            let settings = EvaluatorSettings::default();
1017            let serialized = toml::to_string(&settings).unwrap();
1018            assert!(!serialized.contains("inline_numerator_functions"));
1019            assert_eq!(
1020                toml::from_str::<EvaluatorSettings>(&serialized).unwrap(),
1021                settings
1022            );
1023
1024            let settings: EvaluatorSettings =
1025                toml::from_str("inline_numerator_functions = false").unwrap();
1026            let serialized = toml::to_string(&settings).unwrap();
1027            assert!(serialized.contains("inline_numerator_functions = false"));
1028            assert_eq!(
1029                toml::from_str::<EvaluatorSettings>(&serialized).unwrap(),
1030                settings
1031            );
1032        }
1033
1034        let _guard = ShowDefaultsGuard::new(true);
1035        let serialized = toml::to_string(&EvaluatorSettings::default()).unwrap();
1036        assert!(serialized.contains("inline_numerator_functions = true"));
1037    }
1038
1039    #[test]
1040    fn test_encode_decode_amplitude_graph() {
1041        test_initialise().unwrap();
1042        // Use the model routing produced by graph import for the persistence roundtrip.
1043        let model = load_generic_model("sm");
1044
1045        let graph: Graph = crate::graph::Graph::import_dot(
1046            stringify!(
1047                digraph G{
1048                    e1      [style=invis]
1049                    e2      [style=invis]
1050                    e1 -> n1  [particle=H]
1051                    n4 -> e2    [particle=H]
1052                    n1 -> n2    [particle=H]
1053                    n1 -> n3    [particle=H]
1054                    n2 -> n3    [particle=t]
1055                    n3 -> n4    [particle=t]
1056                    n4 -> n2    [particle=t]
1057                }
1058            ),
1059            &crate::utils::load_generic_model("sm"),
1060        )
1061        .map(|mut graphs| {
1062            assert_eq!(graphs.len(), 1);
1063            graphs.remove(0)
1064        })
1065        .unwrap();
1066        let mut amplitude: AmplitudeGraph = AmplitudeGraph::new(graph.clone());
1067
1068        amplitude
1069            .preprocess(
1070                &model,
1071                &GenerationSettings {
1072                    compile: GammaloopCompileOptions {
1073                        compilation_mode: CompilationMode::Cpp,
1074                        jit_direct_translation: true,
1075                        fast_math: false,
1076                        optimization_level: CompilationOptimizationLevel::O0,
1077                        unsafe_math: false,
1078                        compiler: crate::settings::global::default_external_compiler().to_owned(),
1079                        custom: Vec::new(),
1080                    },
1081                    tropical_subgraph_table: TropicalSubgraphTableSettings {
1082                        panic_on_fail: false,
1083                        target_omega: 1.0,
1084                        ..Default::default()
1085                    },
1086                    ..Default::default()
1087                },
1088                &LockedRuntimeSettings::from(&RuntimeSettings::default()),
1089            )
1090            .unwrap();
1091
1092        let mut symbols = Vec::new();
1093        State::export(&mut symbols).unwrap();
1094        let state_map = State::import(&mut std::io::Cursor::new(symbols), None).unwrap();
1095
1096        let context = GammaLoopContextContainer {
1097            model: &Arc::new(model.clone()),
1098            state_map: &state_map,
1099        };
1100
1101        let encoded_amplitude =
1102            bincode::encode_to_vec(&amplitude, bincode::config::standard()).unwrap();
1103
1104        let decoded: AmplitudeGraph = bincode::decode_from_slice_with_context(
1105            &encoded_amplitude,
1106            bincode::config::standard(),
1107            context,
1108        )
1109        .expect("amplitude decode failed")
1110        .0;
1111
1112        assert_eq!(decoded.graph.name, amplitude.graph.name);
1113        assert_eq!(decoded.graph.overall_factor, amplitude.graph.overall_factor);
1114        assert_eq!(
1115            decoded.graph.loop_momentum_basis,
1116            amplitude.graph.loop_momentum_basis
1117        );
1118        assert_eq!(
1119            decoded.graph.param_builder.reps,
1120            amplitude.graph.param_builder.reps
1121        );
1122        assert_eq!(
1123            decoded.graph.param_builder.values,
1124            amplitude.graph.param_builder.values
1125        );
1126        assert_eq!(
1127            decoded
1128                .derived_data
1129                .representations
1130                .keys()
1131                .collect::<Vec<_>>(),
1132            amplitude
1133                .derived_data
1134                .representations
1135                .keys()
1136                .collect::<Vec<_>>()
1137        );
1138        for (representation, expected) in &amplitude.derived_data.representations {
1139            assert_eq!(
1140                decoded.derived_data.representations[representation].all_mighty_integrand,
1141                expected.all_mighty_integrand
1142            );
1143        }
1144    }
1145}