1use std::{
2 collections::{BTreeMap, BTreeSet},
3 fmt,
4 ops::RangeInclusive,
5 sync::{
6 Arc,
7 atomic::{AtomicBool, Ordering},
8 },
9};
10
11use feynkit_graph::{DiagramId, EdgeId, symbols};
12use feynkit_model::Model;
13use serde::{Deserialize, Serialize};
14use symbolica::atom::{Atom, AtomCore};
15use symbolica::graph::Graph;
16
17use crate::{
18 EdgeColor, GenerationError, NodeColor, ParticleSelector, SelectorError, VertexSelector,
19};
20
21#[derive(
22 Debug,
23 Clone,
24 PartialEq,
25 Eq,
26 Serialize,
27 Deserialize,
28 bincode_trait_derive::Encode,
29 bincode_trait_derive::Decode,
30)]
31pub struct GraphGroupingOptions {
32 pub numerical_sample_seed: u16,
33 pub number_of_numerical_samples: usize,
35 pub differentiate_particle_masses_only: bool,
36 pub fully_numerical_substitution: bool,
37 pub check_canonical_numerator: bool,
40 pub symmetric_polarizations: bool,
42}
43
44impl Default for GraphGroupingOptions {
45 fn default() -> Self {
46 Self {
47 numerical_sample_seed: 3,
48 number_of_numerical_samples: 5,
49 differentiate_particle_masses_only: true,
50 fully_numerical_substitution: false,
51 check_canonical_numerator: false,
52 symmetric_polarizations: false,
53 }
54 }
55}
56
57#[derive(
58 Debug,
59 Clone,
60 Default,
61 PartialEq,
62 Eq,
63 Serialize,
64 Deserialize,
65 bincode_trait_derive::Encode,
66 bincode_trait_derive::Decode,
67)]
68#[serde(rename_all = "snake_case")]
69pub enum NumeratorGrouping {
70 #[default]
71 None,
72 Identical(GraphGroupingOptions),
73 UpToSign(GraphGroupingOptions),
74 UpToScalar(GraphGroupingOptions),
75}
76
77impl NumeratorGrouping {
78 pub fn validate_sample_count(&self) -> Result<(), GenerationError> {
104 let (options, scalar) = match self {
105 NumeratorGrouping::None => return Ok(()),
106 NumeratorGrouping::Identical(options) | NumeratorGrouping::UpToSign(options) => {
107 (options, false)
108 }
109 NumeratorGrouping::UpToScalar(options) => (options, true),
110 };
111 match options.number_of_numerical_samples {
112 0 if !options.check_canonical_numerator => {
113 Err(GenerationError::InvalidNumericalSampleCount)
114 }
115 1 if scalar => Err(GenerationError::SingleSampleScalarRescaling),
116 _ => Ok(()),
117 }
118 }
119
120 pub fn single_sample_warning(&self) -> Option<&'static str> {
138 match self {
139 NumeratorGrouping::Identical(options) | NumeratorGrouping::UpToSign(options)
140 if options.number_of_numerical_samples == 1 =>
141 {
142 Some(
143 "numerator grouping compares a single numerical sample: it accepts only equal or opposite numerators, but cannot tell an identity from a coincidence at that point; use at least two samples",
144 )
145 }
146 NumeratorGrouping::None
147 | NumeratorGrouping::Identical(_)
148 | NumeratorGrouping::UpToSign(_)
149 | NumeratorGrouping::UpToScalar(_) => None,
150 }
151 }
152}
153
154#[derive(
155 Debug,
156 Clone,
157 Copy,
158 PartialEq,
159 Eq,
160 Serialize,
161 Deserialize,
162 bincode_trait_derive::Encode,
163 bincode_trait_derive::Decode,
164)]
165pub struct SelfEnergyFilterOptions {
166 pub veto_massive: bool,
167 pub veto_massless: bool,
168 pub only_scaleless: bool,
169}
170
171impl Default for SelfEnergyFilterOptions {
172 fn default() -> Self {
173 Self {
174 veto_massive: true,
175 veto_massless: true,
176 only_scaleless: false,
177 }
178 }
179}
180
181#[derive(
182 Debug,
183 Clone,
184 Copy,
185 PartialEq,
186 Eq,
187 Serialize,
188 Deserialize,
189 bincode_trait_derive::Encode,
190 bincode_trait_derive::Decode,
191)]
192pub struct SnailFilterOptions {
193 pub veto_attached_to_massive: bool,
194 pub veto_attached_to_massless: bool,
195 pub only_scaleless: bool,
196}
197
198impl Default for SnailFilterOptions {
199 fn default() -> Self {
200 Self {
201 veto_attached_to_massive: false,
202 veto_attached_to_massless: true,
203 only_scaleless: false,
204 }
205 }
206}
207
208#[derive(
209 Debug,
210 Clone,
211 Copy,
212 PartialEq,
213 Eq,
214 Serialize,
215 Deserialize,
216 bincode_trait_derive::Encode,
217 bincode_trait_derive::Decode,
218)]
219pub struct TadpoleFilterOptions {
220 pub veto_attached_to_massive: bool,
221 pub veto_attached_to_massless: bool,
222 pub only_scaleless: bool,
223}
224
225#[derive(
226 Debug,
227 Clone,
228 Copy,
229 PartialEq,
230 Eq,
231 Serialize,
232 Deserialize,
233 bincode_trait_derive::Encode,
234 bincode_trait_derive::Decode,
235)]
236pub struct SewnFilterOptions {
237 pub filter_tadpoles: bool,
238}
239
240impl Default for SewnFilterOptions {
241 fn default() -> Self {
242 Self {
243 filter_tadpoles: true,
244 }
245 }
246}
247
248impl Default for TadpoleFilterOptions {
249 fn default() -> Self {
250 Self {
251 veto_attached_to_massive: true,
252 veto_attached_to_massless: true,
253 only_scaleless: false,
254 }
255 }
256}
257
258#[derive(
259 Debug,
260 Clone,
261 PartialEq,
262 Eq,
263 Serialize,
264 Deserialize,
265 bincode_trait_derive::Encode,
266 bincode_trait_derive::Decode,
267)]
268#[serde(rename_all = "snake_case")]
269pub enum GenerationFilter {
270 SelfEnergy(SelfEnergyFilterOptions),
271 Tadpoles(TadpoleFilterOptions),
272 ZeroSnails(SnailFilterOptions),
273 Sewn(SewnFilterOptions),
274 ParticleVeto(Vec<ParticleSelector>),
275 VertexAllow(Vec<VertexSelector>),
276 VertexVeto(Vec<VertexSelector>),
277 MaxNumberOfBridges(usize),
278 CouplingOrders(BTreeMap<String, (usize, Option<usize>)>),
279 LoopCountRange((usize, usize)),
280 BlobRange(RangeInclusive<usize>),
281 SpectatorRange(RangeInclusive<usize>),
282 PerturbativeOrders(BTreeMap<String, usize>),
283 FermionLoopCountRange((usize, usize)),
284 FactorizedLoopTopologiesCountRange((usize, usize)),
285 LoopOneParticleIrreducible,
288}
289
290#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
291#[serde(rename_all = "snake_case")]
292pub enum FilterScope {
293 Graph,
294 CutAmplitude,
295}
296
297impl fmt::Display for FilterScope {
298 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
299 formatter.write_str(match self {
300 Self::Graph => "graph",
301 Self::CutAmplitude => "cut amplitude",
302 })
303 }
304}
305
306#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
307#[serde(rename_all = "snake_case")]
308pub enum GenerationFilterKind {
309 SelfEnergy,
310 Tadpoles,
311 ZeroSnails,
312 Sewn,
313 ParticleVeto,
314 VertexAllow,
315 VertexVeto,
316 MaxNumberOfBridges,
317 CouplingOrders,
318 LoopCountRange,
319 BlobRange,
320 SpectatorRange,
321 PerturbativeOrders,
322 FermionLoopCountRange,
323 FactorizedLoopTopologiesCountRange,
324 LoopOneParticleIrreducible,
325}
326
327impl fmt::Display for GenerationFilterKind {
328 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
329 formatter.write_str(match self {
330 Self::SelfEnergy => "self_energy",
331 Self::Tadpoles => "tadpoles",
332 Self::ZeroSnails => "zero_snails",
333 Self::Sewn => "sewn",
334 Self::ParticleVeto => "particle_veto",
335 Self::VertexAllow => "vertex_allow",
336 Self::VertexVeto => "vertex_veto",
337 Self::MaxNumberOfBridges => "max_number_of_bridges",
338 Self::LoopOneParticleIrreducible => "loop_one_particle_irreducible",
339 Self::CouplingOrders => "coupling_orders",
340 Self::LoopCountRange => "loop_count_range",
341 Self::BlobRange => "blob_range",
342 Self::SpectatorRange => "spectator_range",
343 Self::PerturbativeOrders => "perturbative_orders",
344 Self::FermionLoopCountRange => "fermion_loop_count_range",
345 Self::FactorizedLoopTopologiesCountRange => "factorized_loop_topologies_count_range",
346 })
347 }
348}
349
350impl GenerationFilter {
351 pub const fn kind(&self) -> GenerationFilterKind {
352 match self {
353 Self::SelfEnergy(_) => GenerationFilterKind::SelfEnergy,
354 Self::Tadpoles(_) => GenerationFilterKind::Tadpoles,
355 Self::ZeroSnails(_) => GenerationFilterKind::ZeroSnails,
356 Self::Sewn(_) => GenerationFilterKind::Sewn,
357 Self::ParticleVeto(_) => GenerationFilterKind::ParticleVeto,
358 Self::VertexAllow(_) => GenerationFilterKind::VertexAllow,
359 Self::VertexVeto(_) => GenerationFilterKind::VertexVeto,
360 Self::MaxNumberOfBridges(_) => GenerationFilterKind::MaxNumberOfBridges,
361 Self::LoopOneParticleIrreducible => GenerationFilterKind::LoopOneParticleIrreducible,
362 Self::CouplingOrders(_) => GenerationFilterKind::CouplingOrders,
363 Self::LoopCountRange(_) => GenerationFilterKind::LoopCountRange,
364 Self::BlobRange(_) => GenerationFilterKind::BlobRange,
365 Self::SpectatorRange(_) => GenerationFilterKind::SpectatorRange,
366 Self::PerturbativeOrders(_) => GenerationFilterKind::PerturbativeOrders,
367 Self::FermionLoopCountRange(_) => GenerationFilterKind::FermionLoopCountRange,
368 Self::FactorizedLoopTopologiesCountRange(_) => {
369 GenerationFilterKind::FactorizedLoopTopologiesCountRange
370 }
371 }
372 }
373}
374
375impl fmt::Display for GenerationFilter {
376 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
377 write!(formatter, "{self:?}")
378 }
379}
380
381#[derive(Debug, Clone, Copy, PartialEq, Eq)]
382pub struct GenerationProgress {
383 pub stage: &'static str,
385 pub completed: usize,
387 pub total: Option<usize>,
390 pub zero_numerator_count: usize,
392}
393
394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
395pub enum GenerationControl {
396 Continue,
397 Cancel,
398}
399
400#[derive(Debug, Clone, Default)]
402pub struct CancellationToken(Arc<AtomicBool>);
403
404impl CancellationToken {
405 pub fn new() -> Self {
406 Self::default()
407 }
408
409 pub fn cancel(&self) {
410 self.0.store(true, Ordering::Release);
411 }
412
413 pub fn is_cancelled(&self) -> bool {
414 self.0.load(Ordering::Acquire)
415 }
416}
417
418type ProgressCallback =
419 Arc<dyn Fn(GenerationProgress) -> GenerationControl + Send + Sync + 'static>;
420type TopologyFilter =
421 Arc<dyn Fn(&Graph<NodeColor, EdgeColor>, usize) -> bool + Send + Sync + 'static>;
422type CancellationCheck = Arc<dyn Fn() -> bool + Send + Sync + 'static>;
423
424#[derive(Clone)]
425pub struct GenerationOptions {
426 pub(crate) threads: Option<usize>,
427 pub(crate) max_vertices: Option<usize>,
428 symmetrize_initial: bool,
429 symmetrize_final: bool,
430 symmetrize_left_right: bool,
431 symmetrize_external_fermions: bool,
432
433 pub(crate) allow_self_loops: bool,
434 pub(crate) allow_zero_flow_edges: bool,
435 pub(crate) graph_filters: Vec<GenerationFilter>,
436 pub(crate) cut_amplitude_filters: Vec<GenerationFilter>,
437 pub(crate) numerator_grouping: NumeratorGrouping,
438 pub(crate) filter_zero_color: bool,
439 pub(crate) graph_prefix: String,
440 pub(crate) selected_diagram_ids: Option<BTreeSet<DiagramId>>,
441 pub(crate) selected_diagram_names: Option<BTreeSet<String>>,
442 pub(crate) vetoed_diagram_ids: BTreeSet<DiagramId>,
443 pub(crate) vetoed_diagram_names: BTreeSet<String>,
444 pub(crate) loop_momentum_bases: BTreeMap<DiagramId, Vec<EdgeId>>,
445 pub(crate) named_loop_momentum_bases: BTreeMap<String, Vec<EdgeId>>,
446 pub(crate) forced_cuts: Vec<BTreeSet<EdgeId>>,
447 pub(crate) numerator_prefactor: Atom,
448 pub(crate) projector: Option<Atom>,
449 pub(crate) cancellation: CancellationToken,
450 pub(crate) cancellation_check: Option<CancellationCheck>,
451 pub(crate) progress: Option<ProgressCallback>,
452 pub(crate) filter: Option<TopologyFilter>,
453}
454
455#[derive(
459 Serialize,
460 Deserialize,
461 PartialEq,
462 Eq,
463 bincode_trait_derive::Encode,
464 bincode_trait_derive::Decode,
465)]
466struct GenerationOptionsPersistent {
467 threads: Option<usize>,
468 max_vertices: Option<usize>,
469 symmetrize_initial: bool,
470 symmetrize_final: bool,
471 symmetrize_left_right: bool,
472 symmetrize_external_fermions: bool,
473
474 allow_self_loops: bool,
475 allow_zero_flow_edges: bool,
476 graph_filters: Vec<GenerationFilter>,
477 cut_amplitude_filters: Vec<GenerationFilter>,
478 numerator_grouping: NumeratorGrouping,
479 #[serde(default)]
480 filter_zero_color: bool,
481 graph_prefix: String,
482 selected_diagram_ids: Option<BTreeSet<u128>>,
483 selected_diagram_names: Option<BTreeSet<String>>,
484 vetoed_diagram_ids: BTreeSet<u128>,
485 vetoed_diagram_names: BTreeSet<String>,
486 loop_momentum_bases: BTreeMap<u128, Vec<usize>>,
487 named_loop_momentum_bases: BTreeMap<String, Vec<usize>>,
488 forced_cuts: Vec<BTreeSet<usize>>,
489 numerator_prefactor: String,
490 projector: Option<String>,
491}
492
493impl From<&GenerationOptions> for GenerationOptionsPersistent {
494 fn from(options: &GenerationOptions) -> Self {
495 Self {
496 threads: options.threads,
497 max_vertices: options.max_vertices,
498 symmetrize_initial: options.symmetrize_initial,
499 symmetrize_final: options.symmetrize_final,
500 symmetrize_left_right: options.symmetrize_left_right,
501 symmetrize_external_fermions: options.symmetrize_external_fermions,
502
503 allow_self_loops: options.allow_self_loops,
504 allow_zero_flow_edges: options.allow_zero_flow_edges,
505 graph_filters: options.graph_filters.clone(),
506 cut_amplitude_filters: options.cut_amplitude_filters.clone(),
507 numerator_grouping: options.numerator_grouping.clone(),
508 filter_zero_color: options.filter_zero_color,
509 graph_prefix: options.graph_prefix.clone(),
510 selected_diagram_ids: options
511 .selected_diagram_ids
512 .as_ref()
513 .map(|ids| ids.iter().map(|id| id.0).collect()),
514 selected_diagram_names: options.selected_diagram_names.clone(),
515 vetoed_diagram_ids: options.vetoed_diagram_ids.iter().map(|id| id.0).collect(),
516 vetoed_diagram_names: options.vetoed_diagram_names.clone(),
517 loop_momentum_bases: options
518 .loop_momentum_bases
519 .iter()
520 .map(|(id, edges)| (id.0, edges.iter().map(|edge| edge.0).collect()))
521 .collect(),
522 named_loop_momentum_bases: options
523 .named_loop_momentum_bases
524 .iter()
525 .map(|(name, edges)| {
526 (
527 name.clone(),
528 edges.iter().map(|edge| edge.0).collect::<Vec<_>>(),
529 )
530 })
531 .collect(),
532 forced_cuts: options
533 .forced_cuts
534 .iter()
535 .map(|cut| cut.iter().map(|edge| edge.0).collect())
536 .collect(),
537 numerator_prefactor: options.numerator_prefactor.to_canonical_string(),
538 projector: options
539 .projector
540 .as_ref()
541 .map(AtomCore::to_canonical_string),
542 }
543 }
544}
545
546impl Serialize for GenerationOptions {
547 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
548 where
549 S: serde::Serializer,
550 {
551 GenerationOptionsPersistent::from(self).serialize(serializer)
552 }
553}
554
555impl<'de> Deserialize<'de> for GenerationOptions {
556 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
557 where
558 D: serde::Deserializer<'de>,
559 {
560 Self::from_persistent(GenerationOptionsPersistent::deserialize(deserializer)?)
561 .map_err(serde::de::Error::custom)
562 }
563}
564
565impl bincode::Encode for GenerationOptions {
566 fn encode<E: bincode::enc::Encoder>(
567 &self,
568 encoder: &mut E,
569 ) -> Result<(), bincode::error::EncodeError> {
570 bincode::Encode::encode(&GenerationOptionsPersistent::from(self), encoder)
571 }
572}
573
574impl<Context> bincode::Decode<Context> for GenerationOptions {
575 fn decode<D: bincode::de::Decoder<Context = Context>>(
576 decoder: &mut D,
577 ) -> Result<Self, bincode::error::DecodeError> {
578 Self::from_persistent(bincode::Decode::decode(decoder)?)
579 .map_err(bincode::error::DecodeError::OtherString)
580 }
581}
582
583bincode::impl_borrow_decode!(GenerationOptions);
584
585impl PartialEq for GenerationOptions {
586 fn eq(&self, other: &Self) -> bool {
587 GenerationOptionsPersistent::from(self) == GenerationOptionsPersistent::from(other)
588 }
589}
590
591impl Eq for GenerationOptions {}
592
593impl Default for GenerationOptions {
594 fn default() -> Self {
595 Self {
596 threads: None,
597 max_vertices: None,
598 symmetrize_initial: false,
599 symmetrize_final: false,
600 symmetrize_left_right: false,
601 symmetrize_external_fermions: false,
602
603 allow_self_loops: false,
604 allow_zero_flow_edges: false,
605 graph_filters: Vec::new(),
606 cut_amplitude_filters: Vec::new(),
607 numerator_grouping: NumeratorGrouping::None,
608 filter_zero_color: false,
609 graph_prefix: "D".to_owned(),
610 selected_diagram_ids: None,
611 selected_diagram_names: None,
612 vetoed_diagram_ids: BTreeSet::new(),
613 vetoed_diagram_names: BTreeSet::new(),
614 loop_momentum_bases: BTreeMap::new(),
615 named_loop_momentum_bases: BTreeMap::new(),
616 forced_cuts: Vec::new(),
617 numerator_prefactor: Atom::one(),
618 projector: None,
619 cancellation: CancellationToken::new(),
620 cancellation_check: None,
621 progress: None,
622 filter: None,
623 }
624 }
625}
626
627impl GenerationOptions {
628 pub fn with_loop_count(
629 mut self,
630 minimum: usize,
631 maximum: usize,
632 ) -> Result<Self, crate::ProcessError> {
633 if minimum > maximum {
634 return Err(crate::ProcessError::InvalidLoopRange { minimum, maximum });
635 }
636 self.graph_filters
637 .retain(|filter| !matches!(filter, GenerationFilter::LoopCountRange(_)));
638 self.graph_filters
639 .push(GenerationFilter::LoopCountRange((minimum, maximum)));
640 Ok(self)
641 }
642
643 pub fn symmetrize_initial(mut self, enabled: bool) -> Self {
644 self.symmetrize_initial = enabled;
645 self
646 }
647
648 pub fn symmetrize_final(mut self, enabled: bool) -> Self {
649 self.symmetrize_final = enabled;
650 self
651 }
652
653 pub fn symmetrize_left_right(mut self, enabled: bool) -> Self {
654 self.symmetrize_left_right = enabled;
655 self
656 }
657
658 pub fn symmetrize_external_fermions(mut self, enabled: bool) -> Self {
664 self.symmetrize_external_fermions = enabled;
665 self
666 }
667
668 pub fn loop_count(&self) -> RangeInclusive<usize> {
669 self.graph_filters
670 .iter()
671 .find_map(|filter| match filter {
672 GenerationFilter::LoopCountRange((minimum, maximum)) => Some(*minimum..=*maximum),
673 _ => None,
674 })
675 .unwrap_or(0..=0)
676 }
677
678 pub fn symmetrizes_initial(&self) -> bool {
679 self.symmetrize_initial
680 }
681
682 pub fn symmetrizes_final(&self) -> bool {
683 self.symmetrize_final
684 }
685
686 pub fn symmetrizes_left_right(&self) -> bool {
687 self.symmetrize_left_right
688 }
689
690 pub fn grouping(&self) -> &NumeratorGrouping {
698 &self.numerator_grouping
699 }
700
701 pub fn symmetrizes_external_fermions(&self) -> bool {
702 self.symmetrize_external_fermions
703 }
704
705 fn from_persistent(persistent: GenerationOptionsPersistent) -> Result<Self, String> {
706 let parse = |expression: String, field: &str| {
707 symbols::parse_expression(&expression, "feynkit_generation_options", None)
708 .map_err(|message| format!("failed to parse {field} '{expression}': {message}"))
709 };
710 Ok(Self {
711 threads: persistent.threads,
712 max_vertices: persistent.max_vertices,
713 symmetrize_initial: persistent.symmetrize_initial,
714 symmetrize_final: persistent.symmetrize_final,
715 symmetrize_left_right: persistent.symmetrize_left_right,
716 symmetrize_external_fermions: persistent.symmetrize_external_fermions,
717
718 allow_self_loops: persistent.allow_self_loops,
719 allow_zero_flow_edges: persistent.allow_zero_flow_edges,
720 graph_filters: persistent.graph_filters,
721 cut_amplitude_filters: persistent.cut_amplitude_filters,
722 numerator_grouping: persistent.numerator_grouping,
723 filter_zero_color: persistent.filter_zero_color,
724 graph_prefix: persistent.graph_prefix,
725 selected_diagram_ids: persistent
726 .selected_diagram_ids
727 .map(|ids| ids.into_iter().map(DiagramId).collect()),
728 selected_diagram_names: persistent.selected_diagram_names,
729 vetoed_diagram_ids: persistent
730 .vetoed_diagram_ids
731 .into_iter()
732 .map(DiagramId)
733 .collect(),
734 vetoed_diagram_names: persistent.vetoed_diagram_names,
735 loop_momentum_bases: persistent
736 .loop_momentum_bases
737 .into_iter()
738 .map(|(id, edges)| {
739 (
740 DiagramId(id),
741 edges.into_iter().map(EdgeId).collect::<Vec<_>>(),
742 )
743 })
744 .collect(),
745 named_loop_momentum_bases: persistent
746 .named_loop_momentum_bases
747 .into_iter()
748 .map(|(name, edges)| (name, edges.into_iter().map(EdgeId).collect()))
749 .collect(),
750 forced_cuts: persistent
751 .forced_cuts
752 .into_iter()
753 .map(|cut| cut.into_iter().map(EdgeId).collect())
754 .collect(),
755 numerator_prefactor: parse(persistent.numerator_prefactor, "numerator prefactor")?,
756 projector: persistent
757 .projector
758 .map(|projector| parse(projector, "projector"))
759 .transpose()?,
760 cancellation: CancellationToken::new(),
761 cancellation_check: None,
762 progress: None,
763 filter: None,
764 })
765 }
766
767 pub(crate) fn resolve_selectors(&self, model: &Model) -> Result<Self, SelectorError> {
769 fn resolve_filter(
770 filter: &GenerationFilter,
771 model: &Model,
772 ) -> Result<GenerationFilter, SelectorError> {
773 Ok(match filter {
774 GenerationFilter::ParticleVeto(selectors) => GenerationFilter::ParticleVeto(
775 selectors
776 .iter()
777 .map(|selector| ParticleSelector::by_id(model, selector.resolve(model)?))
778 .collect::<Result<_, _>>()?,
779 ),
780 GenerationFilter::VertexAllow(selectors) => GenerationFilter::VertexAllow(
781 selectors
782 .iter()
783 .map(|selector| VertexSelector::by_id(model, selector.resolve(model)?))
784 .collect::<Result<_, _>>()?,
785 ),
786 GenerationFilter::VertexVeto(selectors) => GenerationFilter::VertexVeto(
787 selectors
788 .iter()
789 .map(|selector| VertexSelector::by_id(model, selector.resolve(model)?))
790 .collect::<Result<_, _>>()?,
791 ),
792 other => other.clone(),
793 })
794 }
795
796 let mut resolved = self.clone();
797 resolved.graph_filters = self
798 .graph_filters
799 .iter()
800 .map(|filter| resolve_filter(filter, model))
801 .collect::<Result<_, _>>()?;
802 resolved.cut_amplitude_filters = self
803 .cut_amplitude_filters
804 .iter()
805 .map(|filter| resolve_filter(filter, model))
806 .collect::<Result<_, _>>()?;
807 Ok(resolved)
808 }
809}
810
811impl fmt::Debug for GenerationOptions {
812 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
813 formatter
814 .debug_struct("GenerationOptions")
815 .field("threads", &self.threads)
816 .field("max_vertices", &self.max_vertices)
817 .field("allow_self_loops", &self.allow_self_loops)
818 .field("allow_zero_flow_edges", &self.allow_zero_flow_edges)
819 .field("graph_filters", &self.graph_filters)
820 .field("cut_amplitude_filters", &self.cut_amplitude_filters)
821 .field("numerator_grouping", &self.numerator_grouping)
822 .field("filter_zero_color", &self.filter_zero_color)
823 .field("graph_prefix", &self.graph_prefix)
824 .field("selected_diagram_ids", &self.selected_diagram_ids)
825 .field("selected_diagram_names", &self.selected_diagram_names)
826 .field("vetoed_diagram_ids", &self.vetoed_diagram_ids)
827 .field("vetoed_diagram_names", &self.vetoed_diagram_names)
828 .field("loop_momentum_bases", &self.loop_momentum_bases)
829 .field("named_loop_momentum_bases", &self.named_loop_momentum_bases)
830 .field("forced_cuts", &self.forced_cuts)
831 .field("numerator_prefactor", &self.numerator_prefactor)
832 .field("projector", &self.projector)
833 .field("cancelled", &self.cancellation.is_cancelled())
834 .field("cancellation_check", &self.cancellation_check.is_some())
835 .field("progress", &self.progress.is_some())
836 .field("filter", &self.filter.is_some())
837 .finish()
838 }
839}
840
841impl GenerationOptions {
842 pub fn threads(mut self, threads: usize) -> Self {
845 self.threads = Some(threads);
846 self
847 }
848
849 pub fn max_vertices(mut self, max_vertices: usize) -> Self {
850 self.max_vertices = Some(max_vertices);
851 self
852 }
853
854 pub fn allow_self_loops(mut self, allow: bool) -> Self {
855 self.allow_self_loops = allow;
856 self
857 }
858
859 pub fn allow_zero_flow_edges(mut self, allow: bool) -> Self {
860 self.allow_zero_flow_edges = allow;
861 self
862 }
863
864 pub fn with_graph_filter(mut self, filter: GenerationFilter) -> Self {
865 self.graph_filters.push(filter);
866 self
867 }
868
869 pub fn with_cut_amplitude_filter(mut self, filter: GenerationFilter) -> Self {
870 self.cut_amplitude_filters.push(filter);
871 self
872 }
873
874 pub fn with_scoped_filter(self, scope: FilterScope, filter: GenerationFilter) -> Self {
875 match scope {
876 FilterScope::Graph => self.with_graph_filter(filter),
877 FilterScope::CutAmplitude => self.with_cut_amplitude_filter(filter),
878 }
879 }
880
881 pub fn filters(&self, scope: FilterScope) -> &[GenerationFilter] {
882 match scope {
883 FilterScope::Graph => &self.graph_filters,
884 FilterScope::CutAmplitude => &self.cut_amplitude_filters,
885 }
886 }
887
888 pub fn may_filter_covariant_partners(&self) -> bool {
892 self.selected_diagram_ids.is_some()
893 || self.selected_diagram_names.is_some()
894 || !self.vetoed_diagram_ids.is_empty()
895 || !self.vetoed_diagram_names.is_empty()
896 || self.max_vertices.is_some()
897 || self.filter.is_some()
898 || !self.forced_cuts.is_empty()
899 || self
900 .graph_filters
901 .iter()
902 .chain(&self.cut_amplitude_filters)
903 .any(|filter| match filter {
904 GenerationFilter::CouplingOrders(_)
905 | GenerationFilter::LoopCountRange(_)
906 | GenerationFilter::PerturbativeOrders(_) => false,
907 GenerationFilter::VertexAllow(_)
908 | GenerationFilter::LoopOneParticleIrreducible => true,
909 GenerationFilter::VertexVeto(vertices) => !vertices.is_empty(),
910 GenerationFilter::ParticleVeto(particles) => !particles.is_empty(),
911 GenerationFilter::FermionLoopCountRange((minimum, maximum))
912 | GenerationFilter::FactorizedLoopTopologiesCountRange((minimum, maximum)) => {
913 *minimum != 0 || *maximum != usize::MAX
914 }
915 GenerationFilter::BlobRange(range)
916 | GenerationFilter::SpectatorRange(range) => {
917 *range.start() != 0 || *range.end() != usize::MAX
918 }
919 GenerationFilter::MaxNumberOfBridges(maximum) => *maximum != usize::MAX,
920 GenerationFilter::SelfEnergy(options) => {
921 options.veto_massive || options.veto_massless
922 }
923 GenerationFilter::Tadpoles(options) => {
924 options.veto_attached_to_massive || options.veto_attached_to_massless
925 }
926 GenerationFilter::ZeroSnails(options) => {
927 options.veto_attached_to_massive || options.veto_attached_to_massless
928 }
929 GenerationFilter::Sewn(options) => options.filter_tadpoles,
930 })
931 }
932
933 pub fn numerator_grouping(mut self, grouping: NumeratorGrouping) -> Self {
934 self.numerator_grouping = grouping;
935 self
936 }
937
938 pub fn filter_zero_color(mut self, enabled: bool) -> Self {
941 self.filter_zero_color = enabled;
942 self
943 }
944
945 pub fn graph_prefix(mut self, prefix: impl Into<String>) -> Self {
946 self.graph_prefix = prefix.into();
947 self
948 }
949
950 pub fn select_diagrams<I, S>(mut self, names: I) -> Self
952 where
953 I: IntoIterator<Item = S>,
954 S: Into<String>,
955 {
956 self.selected_diagram_names = Some(names.into_iter().map(Into::into).collect());
957 self
958 }
959
960 pub fn select_diagram_ids<I>(mut self, ids: I) -> Self
962 where
963 I: IntoIterator<Item = DiagramId>,
964 {
965 self.selected_diagram_ids = Some(ids.into_iter().collect());
966 self
967 }
968
969 pub fn veto_diagrams<I, S>(mut self, names: I) -> Self
971 where
972 I: IntoIterator<Item = S>,
973 S: Into<String>,
974 {
975 self.vetoed_diagram_names = names.into_iter().map(Into::into).collect();
976 self
977 }
978
979 pub fn veto_diagram_ids<I>(mut self, ids: I) -> Self
981 where
982 I: IntoIterator<Item = DiagramId>,
983 {
984 self.vetoed_diagram_ids = ids.into_iter().collect();
985 self
986 }
987
988 pub fn with_loop_momentum_basis<I>(mut self, diagram: DiagramId, edges: I) -> Self
996 where
997 I: IntoIterator<Item = EdgeId>,
998 {
999 self.loop_momentum_bases
1000 .insert(diagram, edges.into_iter().collect());
1001 self
1002 }
1003
1004 pub fn with_named_loop_momentum_basis<I>(mut self, diagram: impl Into<String>, edges: I) -> Self
1008 where
1009 I: IntoIterator<Item = EdgeId>,
1010 {
1011 self.named_loop_momentum_bases
1012 .insert(diagram.into(), edges.into_iter().collect());
1013 self
1014 }
1015
1016 pub fn forced_cuts<I, C>(mut self, cuts: I) -> Self
1018 where
1019 I: IntoIterator<Item = C>,
1020 C: IntoIterator<Item = EdgeId>,
1021 {
1022 self.forced_cuts = cuts
1023 .into_iter()
1024 .map(|cut| cut.into_iter().collect())
1025 .collect();
1026 self
1027 }
1028
1029 pub fn numerator_prefactor(mut self, prefactor: Atom) -> Self {
1031 self.numerator_prefactor = prefactor;
1032 self
1033 }
1034
1035 pub fn projector(mut self, projector: Atom) -> Self {
1045 self.projector = Some(projector);
1046 self
1047 }
1048
1049 pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
1050 self.cancellation = token;
1051 self
1052 }
1053
1054 pub fn cancellation_check(mut self, check: impl Fn() -> bool + Send + Sync + 'static) -> Self {
1056 self.cancellation_check = Some(Arc::new(check));
1057 self
1058 }
1059
1060 pub fn progress(
1061 mut self,
1062 callback: impl Fn(GenerationProgress) -> GenerationControl + Send + Sync + 'static,
1063 ) -> Self {
1064 self.progress = Some(Arc::new(callback));
1065 self
1066 }
1067
1068 pub fn filter(
1080 mut self,
1081 callback: impl Fn(&Graph<NodeColor, EdgeColor>, usize) -> bool + Send + Sync + 'static,
1082 ) -> Self {
1083 self.filter = Some(Arc::new(callback));
1084 self
1085 }
1086
1087 pub(crate) fn report_progress(
1088 &self,
1089 stage: &'static str,
1090 completed: usize,
1091 total: Option<usize>,
1092 ) {
1093 self.report_progress_with_zero_count(stage, completed, total, 0);
1094 }
1095
1096 pub(crate) fn report_progress_with_zero_count(
1097 &self,
1098 stage: &'static str,
1099 completed: usize,
1100 total: Option<usize>,
1101 zero_numerator_count: usize,
1102 ) {
1103 if self.progress.as_ref().is_some_and(|callback| {
1104 callback(GenerationProgress {
1105 stage,
1106 completed,
1107 total,
1108 zero_numerator_count,
1109 }) == GenerationControl::Cancel
1110 }) {
1111 self.cancellation.cancel();
1112 }
1113 }
1114
1115 pub(crate) fn max_bridges(&self, minimum_loops: usize) -> Option<usize> {
1116 self.graph_filters
1119 .iter()
1120 .filter_map(|filter| match filter {
1121 GenerationFilter::MaxNumberOfBridges(maximum) => Some(*maximum),
1122 GenerationFilter::LoopOneParticleIrreducible if minimum_loops > 0 => Some(0),
1123 _ => None,
1124 })
1125 .min()
1126 }
1127
1128 pub(crate) fn cancellation_requested(&self) -> bool {
1129 if !self.cancellation.is_cancelled()
1130 && self
1131 .cancellation_check
1132 .as_ref()
1133 .is_some_and(|check| check())
1134 {
1135 self.cancellation.cancel();
1138 }
1139 self.cancellation.is_cancelled()
1140 }
1141}
1142
1143#[cfg(test)]
1144mod tests {
1145 #[test]
1146 fn application_cancellation_remains_latched_after_the_signal_clears() {
1147 use std::sync::{
1148 Arc,
1149 atomic::{AtomicBool, Ordering},
1150 };
1151
1152 let signal = Arc::new(AtomicBool::new(true));
1153 let checked = signal.clone();
1154 let options = GenerationOptions::default()
1155 .cancellation_check(move || checked.swap(false, Ordering::AcqRel));
1156 assert!(options.cancellation_requested());
1157 assert!(!signal.load(Ordering::Acquire));
1158 assert!(options.cancellation_requested());
1159 }
1160
1161 #[test]
1162 fn cp_symmetrization_is_an_explicit_serialized_opt_in() {
1163 let options = GenerationOptions::default();
1164 assert!(!options.symmetrizes_left_right());
1165 for enabled in [false, true] {
1166 let options = options.clone().symmetrize_left_right(enabled);
1167 let definition = serde_json::to_value(&options).unwrap();
1168 assert_eq!(definition["symmetrize_left_right"], enabled);
1169 let decoded: GenerationOptions = serde_json::from_value(definition).unwrap();
1170 assert_eq!(decoded.symmetrizes_left_right(), enabled);
1171 }
1172 }
1173
1174 use symbolica::atom::Atom;
1175 use symbolica::parse;
1176
1177 use super::{GenerationFilter, GenerationOptions, GraphGroupingOptions, NumeratorGrouping};
1178 use crate::{ParticleSelector, VertexSelector};
1179 use feynkit_graph::{DiagramId, EdgeId, symbols};
1180
1181 #[test]
1182 fn covariant_partner_diagnostic_distinguishes_orders_from_subsets() {
1183 use super::{FilterScope, SelfEnergyFilterOptions};
1184
1185 let complete = GenerationOptions::default().with_loop_count(0, 2).unwrap();
1186 for scope in [FilterScope::Graph, FilterScope::CutAmplitude] {
1187 let complete = complete
1188 .clone()
1189 .with_scoped_filter(scope, GenerationFilter::CouplingOrders(Default::default()))
1190 .with_scoped_filter(scope, GenerationFilter::ParticleVeto(Vec::new()))
1191 .with_scoped_filter(
1192 scope,
1193 GenerationFilter::SelfEnergy(SelfEnergyFilterOptions {
1194 veto_massive: false,
1195 veto_massless: false,
1196 only_scaleless: true,
1197 }),
1198 );
1199 assert!(!complete.may_filter_covariant_partners());
1200 assert!(
1201 complete
1202 .clone()
1203 .with_scoped_filter(scope, GenerationFilter::VertexAllow(Vec::new()))
1204 .may_filter_covariant_partners()
1205 );
1206 assert!(
1207 complete
1208 .with_scoped_filter(
1209 scope,
1210 GenerationFilter::SelfEnergy(SelfEnergyFilterOptions::default())
1211 )
1212 .may_filter_covariant_partners()
1213 );
1214 }
1215 assert!(
1216 complete
1217 .clone()
1218 .select_diagram_ids([DiagramId(0)])
1219 .may_filter_covariant_partners()
1220 );
1221 assert!(
1222 complete
1223 .clone()
1224 .max_vertices(3)
1225 .may_filter_covariant_partners()
1226 );
1227 assert!(complete.filter(|_, _| true).may_filter_covariant_partners());
1228 }
1229
1230 #[test]
1231 fn zero_color_filter_is_an_explicit_serialized_opt_in() {
1232 let defaults = GenerationOptions::default();
1233 assert!(!defaults.filter_zero_color);
1234 let enabled = defaults.clone().filter_zero_color(true);
1235 assert_ne!(defaults, enabled);
1236 assert!(format!("{enabled:?}").contains("filter_zero_color: true"));
1237 for enabled in [false, true] {
1238 let options = defaults.clone().filter_zero_color(enabled);
1239 let definition = serde_json::to_value(&options).unwrap();
1240 assert_eq!(definition["filter_zero_color"], enabled);
1241 let decoded: GenerationOptions = serde_json::from_value(definition).unwrap();
1242 assert_eq!(decoded, options);
1243 }
1244 let mut definition = serde_json::to_value(&enabled).unwrap();
1245 definition
1246 .as_object_mut()
1247 .unwrap()
1248 .remove("filter_zero_color");
1249 let decoded: GenerationOptions = serde_json::from_value(definition).unwrap();
1250 assert_eq!(decoded, defaults);
1251 }
1252
1253 #[test]
1254 fn zero_count_progress_preserves_callback_cancellation() {
1255 use std::sync::{Arc, Mutex};
1256
1257 let updates = Arc::new(Mutex::new(Vec::new()));
1258 let captured = Arc::clone(&updates);
1259 let options = GenerationOptions::default().progress(move |progress| {
1260 captured.lock().unwrap().push(progress);
1261 if progress.zero_numerator_count == 2 {
1262 super::GenerationControl::Cancel
1263 } else {
1264 super::GenerationControl::Continue
1265 }
1266 });
1267 options.report_progress("numerators", 4, Some(4));
1268 options.report_progress_with_zero_count("filter_zero_color", 1, Some(4), 1);
1269 assert!(!options.cancellation_requested());
1270 options.report_progress_with_zero_count("filter_zero_color", 3, Some(4), 2);
1271 assert!(options.cancellation_requested());
1272 let updates = updates.lock().unwrap();
1273 assert_eq!(updates[0].zero_numerator_count, 0);
1274 assert_eq!(updates[1].zero_numerator_count, 1);
1275 assert_eq!(updates[2].zero_numerator_count, 2);
1276 assert_eq!(updates[2].completed, 3);
1277 assert_eq!(updates[2].total, Some(4));
1278 }
1279
1280 #[test]
1281 fn runtime_callbacks_are_not_serialized() {
1282 let options = GenerationOptions::default()
1283 .filter(|_, _| false)
1284 .progress(|_| super::GenerationControl::Cancel);
1285 let encoded = bincode::encode_to_vec(&options, bincode::config::standard()).unwrap();
1286 let (decoded, _): (GenerationOptions, usize) =
1287 bincode::decode_from_slice(&encoded, bincode::config::standard()).unwrap();
1288 assert_eq!(decoded, options);
1289 assert!(decoded.filter.is_none());
1290 assert!(decoded.progress.is_none());
1291 }
1292
1293 #[test]
1294 fn generation_options_parse_graph_heads_in_symbolic_inputs() {
1295 let mut input = serde_json::to_value(GenerationOptions::default()).unwrap();
1296 input["numerator_prefactor"] = "weight * Q(1)".into();
1297 input["projector"] = "P(0) + experiment::P(0)".into();
1298 let options: GenerationOptions = serde_json::from_value(input).unwrap();
1299
1300 assert_eq!(
1301 options.numerator_prefactor,
1302 parse!("feynkit_generation_options::weight") * symbols::momentum().call(1),
1303 );
1304 assert_eq!(
1305 options.projector,
1306 Some(symbols::external_momentum().call(0) + parse!("experiment::P(0)")),
1307 );
1308 }
1309
1310 #[test]
1311 fn projector_serde_distinguishes_automatic_from_explicit_one() {
1312 let automatic = GenerationOptions::default();
1313 let automatic_json = serde_json::to_string(&automatic).unwrap();
1314 assert!(automatic_json.contains(r#""projector":null"#));
1315 let automatic_roundtrip: GenerationOptions = serde_json::from_str(&automatic_json).unwrap();
1316 assert!(automatic_roundtrip.projector.is_none());
1317
1318 let explicit = GenerationOptions::default().projector(Atom::one());
1319 let explicit_json = serde_json::to_string(&explicit).unwrap();
1320 assert!(explicit_json.contains(r#""projector":"1""#));
1321 let explicit_roundtrip: GenerationOptions = serde_json::from_str(&explicit_json).unwrap();
1322 assert_eq!(explicit_roundtrip.projector, Some(Atom::one()));
1323 }
1324
1325 #[test]
1326 fn bincode_roundtrip_uses_native_enum_encoding() {
1327 let options = GenerationOptions::default()
1328 .threads(3)
1329 .filter_zero_color(true)
1330 .with_graph_filter(GenerationFilter::ParticleVeto(vec![
1331 ParticleSelector::from("g"),
1332 ParticleSelector::from(5_i64),
1333 ]))
1334 .with_cut_amplitude_filter(GenerationFilter::VertexAllow(vec![VertexSelector::from(
1335 "V_42",
1336 )]))
1337 .numerator_grouping(NumeratorGrouping::UpToScalar(
1338 GraphGroupingOptions::default(),
1339 ))
1340 .select_diagram_ids([DiagramId(17)])
1341 .veto_diagram_ids([DiagramId(23)])
1342 .with_loop_momentum_basis(DiagramId(17), [EdgeId(2), EdgeId(7)])
1343 .with_named_loop_momentum_basis("D0", [EdgeId(3), EdgeId(5)])
1344 .forced_cuts([[EdgeId(1), EdgeId(4)]])
1345 .projector(Atom::one());
1346
1347 let encoded = bincode::encode_to_vec(&options, bincode::config::standard()).unwrap();
1348 let (decoded, consumed): (GenerationOptions, usize) =
1349 bincode::decode_from_slice(&encoded, bincode::config::standard()).unwrap();
1350
1351 assert_eq!(consumed, encoded.len());
1352 assert_eq!(decoded, options);
1353 assert!(!decoded.cancellation.is_cancelled());
1354 assert!(decoded.cancellation_check.is_none());
1355 assert!(decoded.progress.is_none());
1356 }
1357}