Skip to main content

feynkit_graph/
compact_dot.rs

1//! Resolve compact physics DOT against a model before ordinary diagram finalization.
2
3use super::*;
4use linnet::half_edge::involution::Hedge;
5use linnet::half_edge::subgraph::ModifySubSet;
6use std::ops::RangeInclusive;
7
8impl FeynmanDiagram {
9    /// Resolve compact physics DOT and retain the exact source-to-final map
10    /// used by finalization. Consumers can transport graph-local metadata
11    /// without reconstructing ownership from momentum or particle labels.
12    /// `final_state` lists comma-separated particles; `|` joins allowed alternatives.
13    pub fn from_compact_dot(
14        model: Arc<Model>,
15        parsed: DotGraph,
16    ) -> Result<(Self, DiagramSourceMap), DiagramError> {
17        let attributes = &parsed.global_data.statements;
18        let mut builder = Self::builder(Arc::clone(&model), parsed.global_data.name.clone());
19        if let Some(value) = attributes.get("overall_factor") {
20            builder.overall_factor =
21                Self::parse_expression(Some(&model), "overall_factor", value.clone())?;
22        }
23        for (attribute, metadata, destination) in [
24            (
25                "num",
26                "numerator_prefactor_interface",
27                &mut builder.numerator_prefactor,
28            ),
29            ("projector", "projector_interface", &mut builder.projector),
30        ] {
31            if let Some(value) = attributes.get(attribute) {
32                *destination = NumeratorInterface::admit(
33                    Self::parse_expression(Some(&model), attribute, value.clone())?,
34                    attributes
35                        .get(metadata)
36                        .map(|value| NumeratorInterface::parse_with_model(value, &model))
37                        .transpose()?,
38                )?;
39            }
40        }
41        let mut nodes = BTreeMap::new();
42        for (node, _, data) in parsed.iter_nodes() {
43            let numerator = NumeratorInterface::admit(
44                Self::parse_expression(
45                    Some(&model),
46                    "vertex numerator",
47                    data.statements
48                        .get("num")
49                        .cloned()
50                        .unwrap_or_else(|| "1".into()),
51                )?,
52                data.statements
53                    .get("num_interface")
54                    .map(|value| NumeratorInterface::parse_with_model(value, &model))
55                    .transpose()?,
56            )?;
57            nodes.insert(
58                node,
59                builder.add_vertex(DiagramVertex {
60                    name: data.name.clone().unwrap_or_else(|| format!("v{}", node.0)),
61                    interaction: None,
62                    numerator,
63                }),
64            );
65        }
66        let mut cut_tags = BTreeMap::new();
67        for (_, edge_id, data) in parsed.iter_edges() {
68            if let Some(value) = data.data.statements.get("is_cut") {
69                let tag =
70                    value
71                        .parse::<usize>()
72                        .map_err(|_| DiagramError::InvalidDotAttribute {
73                            target: format!("edge {}", edge_id.0),
74                            attribute: "is_cut",
75                            value: value.clone(),
76                        })?;
77                cut_tags.insert(tag, 0);
78            }
79        }
80        for (connection, value) in cut_tags.values_mut().enumerate() {
81            *value = connection;
82        }
83        let sewn = !cut_tags.is_empty();
84        let mut next_connection = cut_tags.len();
85        let mut next_external = 0;
86        let mut loop_edges = BTreeMap::new();
87        let mut internal_order = Vec::new();
88        let mut tagged_legs = BTreeMap::<usize, Vec<(Flow, ParticleId)>>::new();
89        for (pair, edge_id, data) in parsed.iter_edges() {
90            let attributes = &data.data.statements;
91            let target = format!("edge {}", edge_id.0);
92            let by_name = attributes
93                .get("particle")
94                .map(|name| model.particle_id(name))
95                .transpose()?;
96            let by_pdg = attributes
97                .get("pdg")
98                .map(|value| {
99                    let pdg =
100                        value
101                            .parse::<i64>()
102                            .map_err(|_| DiagramError::InvalidDotAttribute {
103                                target: target.clone(),
104                                attribute: "pdg",
105                                value: value.clone(),
106                            })?;
107                    model.particle_id_by_pdg(pdg).map_err(DiagramError::from)
108                })
109                .transpose()?;
110            if by_name.is_some() && by_pdg.is_some() && by_name != by_pdg {
111                return Err(DiagramError::InvalidDotAttribute {
112                    target,
113                    attribute: "pdg",
114                    value: "particle and pdg refer to different model particles".into(),
115                });
116            }
117            let particle = by_name
118                .or(by_pdg)
119                .ok_or_else(|| DiagramError::MissingDotAttribute {
120                    target: target.clone(),
121                    attribute: "particle or pdg",
122                })?;
123            let expected_orientation = if model.particle_is_self_conjugate(particle) {
124                Orientation::Undirected
125            } else if model.particle_by_id(particle)?.is_antiparticle() {
126                Orientation::Reversed
127            } else {
128                Orientation::Default
129            };
130            if attributes.contains_key("dir") && data.orientation != expected_orientation {
131                return Err(DiagramError::InvalidDotAttribute {
132                    target,
133                    attribute: "dir",
134                    value: "explicit orientation disagrees with the model particle".into(),
135                });
136            }
137            let mut edge = DiagramEdge::new(particle, !model.particle_is_self_conjugate(particle));
138            edge.numerator = NumeratorInterface::admit(
139                Self::parse_expression(
140                    Some(&model),
141                    "edge numerator",
142                    attributes.get("num").cloned().unwrap_or_else(|| "1".into()),
143                )?,
144                data.data
145                    .statements
146                    .get("num_interface")
147                    .map(|value| NumeratorInterface::parse_with_model(value, &model))
148                    .transpose()?,
149            )?;
150            let tag = attributes
151                .get("is_cut")
152                .map(|value| value.parse::<usize>().expect("validated cut tag"));
153            let (source, sink) = match pair {
154                HedgePair::Paired { source, sink } | HedgePair::Split { source, sink, .. } => {
155                    if tag.is_some() {
156                        return Err(DiagramError::InvalidDotAttribute {
157                            target, attribute: "is_cut", value: "compact cut tags belong on matching incoming/outgoing dangling legs".into(),
158                        });
159                    }
160                    internal_order.push(edge_id.0);
161                    (
162                        Some(nodes[&parsed.node_id(source)]),
163                        Some(nodes[&parsed.node_id(sink)]),
164                    )
165                }
166                HedgePair::Unpaired { hedge, flow } => {
167                    if let Some(tag) = tag {
168                        tagged_legs.entry(tag).or_default().push((flow, particle));
169                    }
170                    let index = next_external;
171                    next_external += 1;
172                    let connection = tag.map(|tag| cut_tags[&tag]).unwrap_or_else(|| {
173                        let connection = next_connection;
174                        next_connection += 1;
175                        connection
176                    });
177                    let state = match flow {
178                        Flow::Sink => ExternalState::Incoming,
179                        Flow::Source => ExternalState::Outgoing,
180                    };
181                    let name = attributes
182                        .get("name")
183                        .cloned()
184                        .unwrap_or_else(|| format!("ext{index}"));
185                    let external = if sewn {
186                        Some(builder.add_generation_external(name, index, state, connection))
187                    } else {
188                        edge.external = Some(ExternalLeg {
189                            name,
190                            index,
191                            state,
192                            connection,
193                        });
194                        None
195                    };
196                    let internal = Some(nodes[&parsed.node_id(hedge)]);
197                    match flow {
198                        Flow::Sink => (external, internal),
199                        Flow::Source => (internal, external),
200                    }
201                }
202            };
203            let added = builder.add_edge(source, sink, edge)?;
204            if let Some(value) = attributes.get("lmb_id") {
205                let slot =
206                    value
207                        .parse::<usize>()
208                        .map_err(|_| DiagramError::InvalidDotAttribute {
209                            target: target.clone(),
210                            attribute: "lmb_id",
211                            value: value.clone(),
212                        })?;
213                if !internal_order.contains(&edge_id.0) || loop_edges.insert(slot, added).is_some()
214                {
215                    return Err(DiagramError::InvalidDotAttribute {
216                        target,
217                        attribute: "lmb_id",
218                        value: "loop slots must be unique and belong to internal edges".into(),
219                    });
220                }
221            }
222        }
223        for (tag, legs) in &tagged_legs {
224            if legs.len() != 2 || legs[0].0 == legs[1].0 || legs[0].1 != legs[1].1 {
225                return Err(DiagramError::InvalidDotAttribute {
226                    target: "external legs".into(),
227                    attribute: "is_cut",
228                    value: format!(
229                        "tag {tag} must pair one incoming and one outgoing leg of the same particle"
230                    ),
231                });
232            }
233        }
234        // Compact DOT omits vertex slots. Match the incident particles to a UFO
235        // rule and assign slots in that rule's order before sewing external legs.
236        for (node, _, data) in parsed.iter_nodes() {
237            let vertex = nodes[&node];
238            let mut incident = Vec::new();
239            for (edge, (endpoints, data)) in builder.edges.iter().enumerate() {
240                if endpoints.source == Some(vertex) {
241                    incident.push((
242                        edge,
243                        true,
244                        model.particle_by_id(data.particle)?.antiparticle,
245                    ));
246                }
247                if endpoints.target == Some(vertex) {
248                    incident.push((edge, false, data.particle));
249                }
250            }
251            let mut signature = incident
252                .iter()
253                .map(|(_, _, particle)| *particle)
254                .collect::<Vec<_>>();
255            signature.sort();
256            let explicit = data
257                .statements
258                .get("int_id")
259                .map(|name| model.vertex_rule_id(name))
260                .transpose()?;
261            let matches = model
262                .vertex_rules()
263                .iter()
264                .enumerate()
265                .filter_map(|(id, rule)| {
266                    let mut particles = rule.particles.clone();
267                    particles.sort();
268                    (particles == signature
269                        && explicit.is_none_or(|explicit| explicit.index() == id))
270                    .then_some(id)
271                })
272                .collect::<Vec<_>>();
273            let [rule] = matches.as_slice() else {
274                return Err(DiagramError::InvalidDotAttribute {
275                    target: format!("vertex {}", builder.vertices[vertex.0].name),
276                    attribute: "int_id",
277                    value: format!(
278                        "incident particles match {} model interactions; specify a matching int_id",
279                        matches.len()
280                    ),
281                });
282            };
283            builder.vertices[vertex.0].interaction = Some(model.vertex_rule_id_at(*rule)?);
284            for (slot, particle) in model.vertex_rules()[*rule].particles.iter().enumerate() {
285                let index = incident
286                    .iter()
287                    .position(|(_, _, candidate)| candidate == particle)
288                    .expect("matched particle signature");
289                let (edge, source, _) = incident.remove(index);
290                if source {
291                    builder.edges[edge].1.source_slot = VertexSlot(slot);
292                } else {
293                    builder.edges[edge].1.target_slot = VertexSlot(slot);
294                }
295            }
296        }
297        if !sewn {
298            builder.half_edge_order = Some(
299                parsed
300                    .iter_hedges()
301                    .map(|(hedge, _)| DiagramHalfEdge {
302                        edge: EdgeId(parsed[&hedge].0),
303                        endpoint: match parsed.flow(hedge) {
304                            Flow::Source => DiagramEndpoint::Source,
305                            Flow::Sink => DiagramEndpoint::Target,
306                        },
307                    })
308                    .collect(),
309            );
310        } else {
311            // Supplied expressions use the parsed DOT half-edge chart. The
312            // generated-vertex finalizer consumes the builder's edge/end chart.
313            // Transport this interface from recorded incidence before sewing;
314            // the finalizer then applies its existing signed ownership map.
315            let source_hedges = parsed
316                .iter_hedges()
317                .map(|(hedge, _)| {
318                    let edge = parsed[&hedge];
319                    let endpoint = usize::from(parsed.flow(hedge) == Flow::Sink);
320                    (hedge.0, 2 * edge.0 + endpoint)
321                })
322                .collect::<BTreeMap<_, _>>();
323            let translate = |atom: &Atom| -> Result<Atom, DiagramError> {
324                let mut invalid = None;
325                let translated = atom.replace_map(|part, _, output| {
326                    let symbolica::atom::AtomView::Fun(index) = part else {
327                        return;
328                    };
329                    if index.get_symbol() != symbols::hedge_index() {
330                        return;
331                    }
332                    let Some(source) = index
333                        .iter()
334                        .next()
335                        .and_then(|arg| usize::try_from(arg).ok())
336                    else {
337                        return;
338                    };
339                    let Some(&target) = source_hedges.get(&source) else {
340                        invalid = Some(source);
341                        return;
342                    };
343                    **output = symbolica::atom::FunctionBuilder::new(symbols::hedge_index())
344                        .add_arg(target)
345                        .add_args(index.iter().skip(1))
346                        .finish();
347                });
348                if let Some(source) = invalid {
349                    return Err(DiagramError::InvalidDotAttribute {
350                        target: "compact numerator interface".into(),
351                        attribute: "num",
352                        value: format!("half-edge {source} is outside the parsed source graph"),
353                    });
354                }
355                Ok(translated)
356            };
357            builder.overall_factor = translate(&builder.overall_factor)?;
358            builder.numerator_prefactor =
359                NumeratorInterface::translate(&builder.numerator_prefactor, translate)?;
360            builder.projector = NumeratorInterface::translate(&builder.projector, translate)?;
361            for vertex in &mut builder.vertices {
362                vertex.numerator = NumeratorInterface::translate(&vertex.numerator, translate)?;
363            }
364            for (_, edge) in &mut builder.edges {
365                edge.numerator = NumeratorInterface::translate(&edge.numerator, translate)?;
366            }
367        }
368        let (mut diagram, source_map) = builder.finalize()?;
369        if attributes.contains_key("projector") && !attributes.contains_key("projector_interface") {
370            // No logical order was declared. Use named algebra order in the
371            // final chart after checked transport has retained index history.
372            diagram.projector = diagram.projector.canonicalize_named_interface();
373        }
374        if !loop_edges.is_empty() {
375            if loop_edges.keys().copied().ne(0..loop_edges.len()) {
376                return Err(DiagramError::InvalidLoopMomentumBasis(
377                    "lmb_id slots must be contiguous from zero".into(),
378                ));
379            }
380            let requested = loop_edges
381                .into_values()
382                .map(|edge| source_map.edges[edge.0])
383                .collect::<Vec<_>>();
384            diagram = diagram.with_loop_momentum_edges(&requested)?;
385        }
386        if sewn {
387            let final_state =
388                attributes
389                    .get("final_state")
390                    .ok_or_else(|| DiagramError::MissingDotAttribute {
391                        target: "compact cross-section graph".into(),
392                        attribute: "final_state",
393                    })?;
394            let final_states = final_state
395                .split('|')
396                .map(|alternative| {
397                    let mut particles = alternative
398                        .split(',')
399                        .map(str::trim)
400                        .map(|name| model.particle_id(name))
401                        .collect::<Result<Vec<_>, _>>()?;
402                    particles.sort();
403                    Ok::<_, ModelError>(particles)
404                })
405                .collect::<Result<BTreeSet<_>, _>>()?;
406            let mut left_nodes = BTreeSet::new();
407            let mut right_nodes = BTreeSet::new();
408            for (_, endpoints, edge) in diagram.edges() {
409                if edge.external.is_some() {
410                    match (endpoints.source, endpoints.target) {
411                        (Some(source), Some(target)) => {
412                            left_nodes.insert(NodeIndex(target.0));
413                            right_nodes.insert(NodeIndex(source.0));
414                        }
415                        _ => {
416                            return Err(DiagramError::InvalidDotAttribute {
417                                target: "external legs".into(),
418                                attribute: "is_cut",
419                                value:
420                                    "all cross-section external legs must have a matching cut tag"
421                                        .into(),
422                            });
423                        }
424                    }
425                }
426            }
427            if !left_nodes.is_disjoint(&right_nodes) {
428                return Err(DiagramError::InvalidCut {
429                    cut: 0,
430                    message: "incoming and outgoing attachments must lie on separate vertices"
431                        .into(),
432                });
433            }
434            let blob_range = match attributes.get("n_cut_blobs") {
435                None => 1..=1,
436                Some(value) => {
437                    parse_blob_range(value).ok_or_else(|| DiagramError::InvalidDotAttribute {
438                        target: "graph".into(),
439                        attribute: "n_cut_blobs",
440                        value: format!(
441                            "{value:?} is not a blob count or an ordered range \"min,max\""
442                        ),
443                    })?
444                }
445            };
446            // The unsewn structure: every sewn external edge r -> l becomes
447            // the legs leg_in -> l and r -> leg_out, after the diagram
448            // vertices. Internal edges keep their diagram edge.
449            let n_nodes = diagram.graph.n_nodes();
450            let mut unsewn = HedgeGraphBuilder::new();
451            for _ in 0..n_nodes {
452                unsewn.add_node(());
453            }
454            let mut incoming = Vec::new();
455            let mut outgoing = Vec::new();
456            for (edge_id, endpoints, edge) in diagram.edges() {
457                let (Some(source), Some(target)) = (endpoints.source, endpoints.target) else {
458                    continue;
459                };
460                let (source, target) = (NodeIndex(source.0), NodeIndex(target.0));
461                if edge.external.is_some() {
462                    let leg = unsewn.add_node(());
463                    unsewn.add_edge(leg, target, None, Orientation::Default);
464                    incoming.push(leg);
465                    let leg = unsewn.add_node(());
466                    unsewn.add_edge(source, leg, None, Orientation::Default);
467                    outgoing.push(leg);
468                } else {
469                    unsewn.add_edge(source, target, Some(edge_id), Orientation::Default);
470                }
471            }
472            let unsewn: HedgeGraph<Option<EdgeId>, ()> = unsewn.build();
473            let forward = ForwardGraph::new(&unsewn, &incoming, &outgoing).map_err(|error| {
474                DiagramError::InvalidCut {
475                    cut: 0,
476                    message: error.to_string(),
477                }
478            })?;
479            let unsewn_half_edges: BTreeMap<EdgeId, Hedge> = unsewn
480                .iter_edges()
481                .filter_map(|(pair, _, data)| match (pair, *data.data) {
482                    (HedgePair::Paired { source, .. }, Some(edge)) => Some((edge, source)),
483                    _ => None,
484                })
485                .collect();
486            // (partition, found only by the search with the legs fixed)
487            let mut partitions = Vec::new();
488            let mut enumerated = BTreeSet::new();
489            for (_, cut, _) in diagram.graph.all_cuts_from_ids(
490                &left_nodes.iter().copied().collect::<Vec<_>>(),
491                &right_nodes.iter().copied().collect::<Vec<_>>(),
492            ) {
493                // The sewn search keeps the far half of a bridge it skips on
494                // the left. Rebuild whole vertex sides on the unsewn structure
495                // from the internal edges the cut crosses.
496                let mut boundary: SuBitGraph = unsewn.empty_subgraph();
497                for hedge in cut.left.included_iter() {
498                    if let Some(&half) = unsewn_half_edges.get(&EdgeId(diagram.graph[&hedge].0)) {
499                        boundary.add(half);
500                    }
501                }
502                if let Some(partition) = forward.partition(&boundary) {
503                    enumerated.insert(partition.cut().clone());
504                    partitions.push((partition, false));
505                }
506            }
507            // As in generation, also enumerate with one fixed degree-one vertex
508            // per leg. The search above grows the left side one vertex at a
509            // time and drops every step whose right side has more components
510            // than the fixed right vertices. With adjacent outgoing
511            // attachments, a subgraph attached only to incoming attachments
512            // (such as a self-energy on the internal line between them) is a
513            // second right component from the start, so it never reaches a
514            // partition that places it on the left.
515            for found in forward.leg_seeded_cuts(|boundary| enumerated.contains(boundary)) {
516                if let LegSeededCut::Partition(partition) = found {
517                    partitions.push((partition, true));
518                }
519            }
520            let vertex_half_edges = diagram.vertex_half_edges();
521            let mut cuts = Vec::new();
522            let mut thresholds = Vec::new();
523            for (partition, recovered) in partitions {
524                let left_vertices = (0..n_nodes)
525                    .map(NodeIndex)
526                    .filter(|&node| {
527                        unsewn
528                            .iter_crown(node)
529                            .any(|hedge| partition.left().includes(&hedge))
530                    })
531                    .collect::<BTreeSet<_>>();
532                let (left, right): (Vec<_>, Vec<_>) = diagram.half_edges().partition(|half| {
533                    let hedge = diagram.half_edge_id(*half).expect("existing half-edge");
534                    left_vertices.contains(&diagram.graph.node_id(hedge))
535                });
536                // Blobs of each side, counted with its legs as generation
537                // counts them.
538                let left_blobs = unsewn.count_connected_components(partition.left());
539                let right_blobs = unsewn.count_connected_components(partition.right());
540                let cut = diagram.cut_from_partitions(
541                    cuts.len(),
542                    &left,
543                    &right,
544                    &vertex_half_edges,
545                    None,
546                )?;
547                let mut content = diagram.cut_particles(&cut)?;
548                content.sort();
549                // Physical cuts follow generation: both sides within the blob
550                // range, with the requested final state.
551                if blob_range.contains(&left_blobs)
552                    && blob_range.contains(&right_blobs)
553                    && final_states.contains(&content)
554                {
555                    cuts.push(cut.clone());
556                }
557                // A recovered threshold candidate needs connected sides,
558                // independently of the blob range.
559                if cut.cut.len() >= 2 && (!recovered || (left_blobs == 1 && right_blobs == 1)) {
560                    thresholds.push((left, right));
561                }
562            }
563            if cuts.is_empty() {
564                return Err(DiagramError::InvalidDotAttribute {
565                    target: "graph".into(),
566                    attribute: "final_state",
567                    value: format!(
568                        "no separating cut has final state {final_state} with {}..={} blobs per side",
569                        blob_range.start(),
570                        blob_range.end()
571                    ),
572                });
573            }
574            diagram = diagram
575                .with_cuts(cuts)?
576                .with_topology_threshold_partitions(thresholds)?;
577        } else if attributes.contains_key("final_state") {
578            return Err(DiagramError::InvalidDotAttribute {
579                target: "graph".into(),
580                attribute: "final_state",
581                value: "final_state requires paired is_cut external legs".into(),
582            });
583        }
584        diagram.validate()?;
585        Ok((diagram, source_map))
586    }
587}
588
589/// A compact `n_cut_blobs` value: one blob count, or the ordered bounds
590/// `min,max`, as `--n-cut-blobs` accepts them in generation.
591fn parse_blob_range(value: &str) -> Option<RangeInclusive<usize>> {
592    let mut bounds = value
593        .split(',')
594        .map(|bound| bound.trim().parse::<usize>().ok());
595    let minimum = bounds.next()??;
596    let maximum = bounds.next().unwrap_or(Some(minimum))?;
597    (bounds.next().is_none() && minimum <= maximum).then_some(minimum..=maximum)
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603    use spenso::structure::abstract_index::{AIND_SYMBOLS, AbstractIndex};
604    use spenso::structure::partial::PartialIndex;
605    use spenso::structure::representation::LibraryRep;
606    use spenso::structure::slot::IsAbstractSlot;
607    use spenso::tensor_symbol;
608    use symbolica::{function, parse};
609
610    #[test]
611    fn compact_dot_resolves_short_names_in_numerators() {
612        let model = Arc::new(
613            Model::from_json(include_str!(
614                "../../feynkit-model/tests/fixtures/scalars_2p_3p.json"
615            ))
616            .unwrap(),
617        );
618        let dot = r#"digraph scalar_propagator {
619            graph [num="SCALAR_COUPLING*(lam+example::lam)"];
620            ext [style=invis];
621            a [num="Q(0,cind(0))"];
622            ext -> a [particle="scalar_1"];
623            a -> ext [particle="scalar_1"];
624        }"#;
625        let diagram = FeynmanDiagram::from_dot(Arc::clone(&model), dot).unwrap();
626        assert_eq!(
627            diagram.numerator().expression(),
628            &function!(symbols::momentum(), 0, function!(AIND_SYMBOLS.cind, 0))
629        );
630        assert_eq!(
631            diagram.numerator_prefactor().expression(),
632            &parse!("UFO::SCALAR_COUPLING*(UFO::lam+example::lam)")
633        );
634        let restored =
635            FeynmanDiagram::from_dot(Arc::clone(&model), &diagram.to_dot().unwrap()).unwrap();
636        assert_eq!(restored.to_json().unwrap(), diagram.to_json().unwrap());
637
638        let mut snapshot = diagram.serde_view();
639        snapshot.projector = "0".into();
640        snapshot.projector_interface = Some(vec!["mink(lam)".into()]);
641        let restored =
642            FeynmanDiagram::from_json(model, &serde_json::to_string(&snapshot).unwrap()).unwrap();
643        let expected = NumeratorInterface::admit(
644            Atom::Zero,
645            Some(NumeratorInterface(vec![parse!("spenso::mink(UFO::lam)")])),
646        )
647        .unwrap();
648        assert!(restored.projector().same_value(&expected));
649    }
650
651    #[test]
652    fn compact_projector_layout_distinguishes_inference_from_declaration() {
653        let model = Arc::new(
654            Model::from_json(include_str!(
655                "../../feynkit-model/tests/fixtures/scalars_2p_3p.json"
656            ))
657            .unwrap(),
658        );
659        let input = r#"digraph projector_bubble {
660            final_state="scalar_1,scalar_1"
661            ext [style=invis]
662            ext -> a:5 [id=0 particle=scalar_1 is_cut=7]
663            a:1 -> b:2 [id=1 particle=scalar_1 lmb_id=0]
664            b:0 -> ext [id=2 particle=scalar_1 is_cut=7]
665            a:3 -> b:4 [id=3 particle=scalar_1]
666        }"#;
667        let rep = Minkowski {}.new_rep(4).cast::<LibraryRep>();
668        let index = |owner| AbstractIndex::Named(symbols::hedge_index().into(), owner, 1);
669        let slot = |owner| rep.slot(PartialIndex::Explicit(index(owner)));
670        let slot_atom = |owner| rep.slot::<AbstractIndex, _>(index(owner)).to_atom();
671        let head = tensor_symbol!("compact_projector_order");
672        let source_owners = [0, 5];
673        let payload = function!(head, slot_atom(0), slot_atom(5));
674        for declaration in [None, Some([0, 1]), Some([1, 0])] {
675            let mut parsed = DotGraph::from_string(input).unwrap();
676            parsed
677                .global_data
678                .statements
679                .insert("projector".into(), payload.to_canonical_string());
680            if let Some(order) = declaration {
681                let interface = NumeratorInterface(
682                    order
683                        .into_iter()
684                        .map(|position| slot_atom(source_owners[position]))
685                        .collect(),
686                );
687                parsed
688                    .global_data
689                    .statements
690                    .insert("projector_interface".into(), interface.to_json());
691            }
692            let (diagram, source_map) =
693                FeynmanDiagram::from_compact_dot(Arc::clone(&model), parsed.clone()).unwrap();
694            // Source h0 belongs to the outgoing leg, h5 to the incoming leg.
695            // Resolve their finalized endpoints independently of tensor transport.
696            let target_owners = [
697                DiagramHalfEdge {
698                    edge: source_map.edges()[2],
699                    endpoint: DiagramEndpoint::Source,
700                },
701                DiagramHalfEdge {
702                    edge: source_map.edges()[0],
703                    endpoint: DiagramEndpoint::Target,
704                },
705            ]
706            .map(|half| diagram.half_edge_id(half).unwrap().0);
707            assert_eq!(target_owners, [5, 0]);
708            let target_ports = target_owners.map(slot);
709            let expected_payload = function!(
710                head,
711                slot_atom(target_owners[0]),
712                slot_atom(target_owners[1])
713            );
714            let expected_order = declaration.unwrap_or([1, 0]);
715            let expected_ports = expected_order.map(|position| target_ports[position]);
716            assert_eq!(diagram.projector().expression(), &expected_payload);
717            assert_eq!(
718                diagram.projector().structure().logical_slots(),
719                expected_ports
720            );
721            if declaration.is_none() {
722                assert_eq!(diagram.projector().presentation_atom(), expected_payload);
723                let (exported, interface) = NumeratorInterface::export(diagram.projector());
724                assert!(
725                    interface.is_some(),
726                    "leaf syntax alone has a different logical order"
727                );
728                let restored = NumeratorInterface::admit(exported, interface).unwrap();
729                assert!(restored.same_value(diagram.projector()));
730            } else {
731                // A declared ranked zero has no payload from which to recover order.
732                parsed
733                    .global_data
734                    .statements
735                    .insert("projector".into(), "0".into());
736                let (zero, _) =
737                    FeynmanDiagram::from_compact_dot(Arc::clone(&model), parsed).unwrap();
738                assert!(zero.projector().is_zero());
739                assert_eq!(zero.projector().structure().logical_slots(), expected_ports);
740            }
741        }
742
743        // An undeclared positional interface must bypass named-axis sorting.
744        let mut parsed = DotGraph::from_string(input).unwrap();
745        let payload = function!(head, rep.to_symbolic([]), slot_atom(0));
746        let source = NumeratorInterface::admit(payload.clone(), None).unwrap();
747        parsed
748            .global_data
749            .statements
750            .insert("projector".into(), payload.to_canonical_string());
751        let (diagram, source_map) = FeynmanDiagram::from_compact_dot(model, parsed).unwrap();
752        let target_owner = diagram
753            .half_edge_id(DiagramHalfEdge {
754                edge: source_map.edges()[2],
755                endpoint: DiagramEndpoint::Source,
756            })
757            .unwrap()
758            .0;
759        let mut expected_ports = source.structure().logical_slots();
760        expected_ports[1] = slot(target_owner);
761        let expected_payload = source
762            .expression()
763            .replace(slot_atom(0).to_pattern())
764            .with(slot_atom(target_owner));
765        assert_eq!(
766            diagram.projector().structure().logical_slots(),
767            expected_ports
768        );
769        assert_eq!(diagram.projector().structure().open_positions(), [0]);
770        assert_eq!(diagram.projector().expression(), &expected_payload);
771    }
772
773    #[test]
774    fn compact_final_state_alternatives_preserve_the_union_of_physical_cuts() {
775        let model = Arc::new(
776            Model::from_json(include_str!(
777                "../../feynkit-model/tests/fixtures/scalars_2p_3p.json"
778            ))
779            .unwrap(),
780        );
781        let input = r#"digraph alternatives {
782            final_state="FINAL_STATE";
783            ext_in [style=invis]; ext_out [style=invis];
784            ext_in -> a [id=0 particle=scalar_1 is_cut=7];
785            a -> b [id=1 particle=scalar_1];
786            a -> d [id=2 particle=scalar_1];
787            b -> c [id=3 particle=scalar_1];
788            b -> c [id=4 particle=scalar_2];
789            c -> d [id=5 particle=scalar_1];
790            d -> ext_out [id=6 particle=scalar_1 is_cut=7];
791        }"#;
792        let load = |states: &str| {
793            FeynmanDiagram::from_compact_dot(
794                Arc::clone(&model),
795                DotGraph::from_string(input.replace("FINAL_STATE", states)).unwrap(),
796            )
797            .map(|(diagram, _)| diagram)
798        };
799        let two = load("scalar_1,scalar_1").unwrap();
800        let three = load("scalar_1,scalar_1,scalar_2").unwrap();
801        let both =
802            load("scalar_1,scalar_1 | scalar_1,scalar_2,scalar_1 | scalar_1,scalar_1").unwrap();
803        assert_eq!(two.cuts().len(), 2);
804        assert_eq!(three.cuts().len(), 1);
805        assert_eq!(
806            both.cuts().iter().cloned().collect::<BTreeSet<_>>(),
807            two.cuts()
808                .iter()
809                .chain(three.cuts())
810                .cloned()
811                .collect::<BTreeSet<_>>(),
812        );
813        assert_eq!(both.loop_momentum_basis(), two.loop_momentum_basis());
814        assert_eq!(both.loop_momentum_basis(), three.loop_momentum_basis());
815        assert_eq!(
816            both.topology_threshold_candidates(),
817            two.topology_threshold_candidates()
818        );
819        assert_eq!(
820            both.topology_threshold_candidates(),
821            three.topology_threshold_candidates()
822        );
823        assert_eq!(both.numerator(), two.numerator());
824        assert!(load("scalar_1,scalar_1|").is_err());
825    }
826
827    #[test]
828    fn compact_self_energies_between_attachments_keep_their_cut_on_either_side() {
829        let model = Arc::new(
830            Model::from_json(include_str!(
831                "../../feynkit-model/tests/fixtures/scalars_2p_3p.json"
832            ))
833            .unwrap(),
834        );
835        // Attachments a, b (incoming) and c, d (outgoing) on one loop
836        // a - c - d - b, closed by a self-energy e = f on the internal line
837        // between either the incoming or the outgoing pair.
838        let incoming_side = r#"digraph incoming_side {
839            final_state="scalar_1,scalar_1";
840            in0 [style=invis]; in1 [style=invis]; out0 [style=invis]; out1 [style=invis];
841            in0 -> a [id=0 particle=scalar_1 is_cut=7];
842            in1 -> b [id=1 particle=scalar_1 is_cut=8];
843            c -> out0 [id=2 particle=scalar_1 is_cut=7];
844            d -> out1 [id=3 particle=scalar_1 is_cut=8];
845            a -> c [id=4 particle=scalar_1];
846            c -> d [id=5 particle=scalar_1];
847            d -> b [id=6 particle=scalar_1];
848            a -> e [id=7 particle=scalar_1];
849            e -> f [id=8 particle=scalar_1];
850            e -> f [id=9 particle=scalar_1];
851            f -> b [id=10 particle=scalar_1];
852        }"#;
853        let outgoing_side = r#"digraph outgoing_side {
854            final_state="scalar_1,scalar_1";
855            in0 [style=invis]; in1 [style=invis]; out0 [style=invis]; out1 [style=invis];
856            in0 -> a [id=0 particle=scalar_1 is_cut=7];
857            in1 -> b [id=1 particle=scalar_1 is_cut=8];
858            c -> out0 [id=2 particle=scalar_1 is_cut=7];
859            d -> out1 [id=3 particle=scalar_1 is_cut=8];
860            a -> c [id=4 particle=scalar_1];
861            a -> b [id=5 particle=scalar_1];
862            b -> d [id=6 particle=scalar_1];
863            c -> e [id=7 particle=scalar_1];
864            e -> f [id=8 particle=scalar_1];
865            e -> f [id=9 particle=scalar_1];
866            f -> d [id=10 particle=scalar_1];
867        }"#;
868        for input in [incoming_side, outgoing_side] {
869            let (diagram, _) = FeynmanDiagram::from_compact_dot(
870                Arc::clone(&model),
871                DotGraph::from_string(input).unwrap(),
872            )
873            .unwrap();
874            assert_eq!(diagram.cuts().len(), 1, "{input}");
875        }
876    }
877
878    #[test]
879    fn compact_multi_blob_cuts_follow_the_declared_blob_range() {
880        let model = Arc::new(
881            Model::from_json(include_str!(
882                "../../feynkit-model/tests/fixtures/scalars_2p_3p.json"
883            ))
884            .unwrap(),
885        );
886        // The incoming-side self-energy graph. With only a and b on the left,
887        // the partition crosses four lines and has two blobs on each side.
888        let input = r#"digraph incoming_side {
889            final_state="STATE"; BLOBS
890            in0 [style=invis]; in1 [style=invis]; out0 [style=invis]; out1 [style=invis];
891            in0 -> a [id=0 particle=scalar_1 is_cut=7];
892            in1 -> b [id=1 particle=scalar_1 is_cut=8];
893            c -> out0 [id=2 particle=scalar_1 is_cut=7];
894            d -> out1 [id=3 particle=scalar_1 is_cut=8];
895            a -> c [id=4 particle=scalar_1];
896            c -> d [id=5 particle=scalar_1];
897            d -> b [id=6 particle=scalar_1];
898            a -> e [id=7 particle=scalar_1];
899            e -> f [id=8 particle=scalar_1];
900            e -> f [id=9 particle=scalar_1];
901            f -> b [id=10 particle=scalar_1];
902        }"#;
903        let load = |state: &str, blobs: &str| {
904            FeynmanDiagram::from_compact_dot(
905                Arc::clone(&model),
906                DotGraph::from_string(input.replace("STATE", state).replace("BLOBS", blobs))
907                    .unwrap(),
908            )
909            .map(|(diagram, _)| diagram)
910        };
911        let four = "scalar_1,scalar_1,scalar_1,scalar_1";
912        assert!(matches!(
913            load(four, ""),
914            Err(DiagramError::InvalidDotAttribute {
915                attribute: "final_state",
916                ..
917            })
918        ));
919        let two_blobs = load(four, r#"n_cut_blobs="1,2";"#).unwrap();
920        assert_eq!(two_blobs.cuts().len(), 1);
921        assert_eq!(two_blobs.cuts()[0].cut.len(), 4);
922        // Threshold candidates need connected sides whatever the blob range:
923        // only the two-body boundary qualifies.
924        let two_body = load("scalar_1,scalar_1", "").unwrap();
925        assert_eq!(two_blobs.topology_threshold_candidates().len(), 1);
926        assert_eq!(
927            two_blobs.topology_threshold_candidates(),
928            two_body.topology_threshold_candidates()
929        );
930        // The same ordered bounds as generation's --n-cut-blobs.
931        for blobs in ["1,2", "0,1", "1"] {
932            assert_eq!(
933                load("scalar_1,scalar_1", &format!(r#"n_cut_blobs="{blobs}";"#))
934                    .unwrap()
935                    .cuts(),
936                two_body.cuts(),
937                "{blobs}"
938            );
939        }
940        for invalid in ["2,1", "1,2,3", "one", "-1"] {
941            assert!(matches!(
942                load(four, &format!(r#"n_cut_blobs="{invalid}";"#)),
943                Err(DiagramError::InvalidDotAttribute {
944                    attribute: "n_cut_blobs",
945                    ..
946                })
947            ));
948        }
949        // Canonical DOT keeps the resolved inventories, not the input filter,
950        // and reproduces itself after import.
951        let canonical = two_blobs.to_dot().unwrap();
952        assert!(!canonical.contains("n_cut_blobs"));
953        let reimported = FeynmanDiagram::from_dot(Arc::clone(&model), &canonical).unwrap();
954        assert_eq!(reimported.cuts(), two_blobs.cuts());
955        assert_eq!(
956            reimported.topology_threshold_candidates(),
957            two_blobs.topology_threshold_candidates()
958        );
959        assert_eq!(reimported.to_dot().unwrap(), canonical);
960    }
961
962    #[test]
963    fn compact_cuts_keep_whole_vertices_behind_bridges() {
964        let model = Arc::new(
965            Model::from_json(include_str!(
966                "../../feynkit-model/tests/fixtures/scalars_2p_3p.json"
967            ))
968            .unwrap(),
969        );
970        // The line a - x - c, the line b - d, a self-energy y = w between c
971        // and d, and a self-loop vertex z attached to x by the bridge x - z.
972        // The attachment search finds both two-body cuts by itself; behind the
973        // cut {x-c, b-d}, z and its self-loop stay with x on the left.
974        let input = r#"digraph attachment_bridge {
975            final_state="scalar_1,scalar_1";
976            in0 [style=invis]; in1 [style=invis]; out0 [style=invis]; out1 [style=invis];
977            in0 -> a [id=0 particle=scalar_1 is_cut=7];
978            in1 -> b [id=1 particle=scalar_1 is_cut=8];
979            c -> out0 [id=2 particle=scalar_1 is_cut=7];
980            d -> out1 [id=3 particle=scalar_1 is_cut=8];
981            a -> b [id=4 particle=scalar_1];
982            a -> x [id=5 particle=scalar_1];
983            x -> c [id=6 particle=scalar_1];
984            b -> d [id=7 particle=scalar_1];
985            c -> y [id=8 particle=scalar_1];
986            y -> w [id=9 particle=scalar_1];
987            y -> w [id=10 particle=scalar_1];
988            w -> d [id=11 particle=scalar_1];
989            x -> z [id=12 particle=scalar_1];
990            z -> z [id=13 particle=scalar_1];
991        }"#;
992        let (diagram, _) = FeynmanDiagram::from_compact_dot(
993            Arc::clone(&model),
994            DotGraph::from_string(input).unwrap(),
995        )
996        .unwrap();
997        let loops = diagram
998            .cuts()
999            .iter()
1000            .map(|cut| [cut.left.loop_count, cut.right.loop_count])
1001            .collect::<BTreeSet<_>>();
1002        assert_eq!(loops, BTreeSet::from([[0, 2], [1, 1]]));
1003    }
1004
1005    #[test]
1006    fn compact_dot_source_map_records_sewing_and_loop_ownership() {
1007        let model = Arc::new(
1008            Model::from_json(include_str!(
1009                "../../feynkit-model/tests/fixtures/scalars_2p_3p.json"
1010            ))
1011            .unwrap(),
1012        );
1013        let input = r#"digraph mapped_bubble {
1014            final_state="scalar_1,scalar_1"
1015            ext [style=invis]
1016            ext -> a [id=0 particle=scalar_1 is_cut=7]
1017            a -> b [id=1 particle=scalar_1 lmb_id=0]
1018            b -> ext [id=2 particle=scalar_1 is_cut=7]
1019            a -> b [id=3 particle=scalar_1]
1020        }"#;
1021        let parsed = DotGraph::from_string(input).unwrap();
1022        let (diagram, source) = FeynmanDiagram::from_compact_dot(model, parsed).unwrap();
1023        assert_eq!(
1024            source.edges(),
1025            &[EdgeId(0), EdgeId(1), EdgeId(0), EdgeId(2)]
1026        );
1027        assert_eq!(
1028            &source.vertices()[..2],
1029            &[Some(VertexId(0)), Some(VertexId(1))]
1030        );
1031        assert_eq!(
1032            diagram.loop_momentum_basis().loop_edges,
1033            [source.edges()[1]]
1034        );
1035        assert_eq!(diagram.edges().count(), 3);
1036        assert!(!diagram.cuts().is_empty());
1037        for cut in diagram.cuts() {
1038            let edges = cut
1039                .cut
1040                .iter()
1041                .map(|half| half.edge)
1042                .collect::<BTreeSet<_>>();
1043            assert_eq!(
1044                edges,
1045                BTreeSet::from([source.edges()[1], source.edges()[3]])
1046            );
1047        }
1048    }
1049}