Skip to main content

feynkit_model/model/
builtins.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use miniz_oxide::inflate::decompress_to_vec_zlib;
4
5use super::{
6    CouplingDefinition as Coupling, LorentzStructureDefinition as LorentzStructure, Model,
7    ModelDefinition, Order, ParameterDefinition as Parameter, ParameterNature, ParameterType,
8    ParticleDefinition as Particle, PropagatorDefinition as Propagator,
9    VertexRuleDefinition as VertexRule,
10};
11use crate::{ComplexValue, ModelError, Particle as ModelParticle};
12
13impl Model {
14    /// Load a fresh copy of the complete embedded Standard Model (`sm`).
15    ///
16    /// Includes 43 particles and 163 vertices with their default parameter
17    /// values. The compressed data is decoded on demand, without file access
18    /// or a Python/UFO runtime.
19    pub fn standard_model() -> Self {
20        let json = decompress_to_vec_zlib(include_bytes!("../../data/sm.json.zlib"))
21            .expect("embedded Standard Model must decompress");
22        let definition =
23            serde_json::from_slice(&json).expect("embedded Standard Model must contain valid JSON");
24        Self::new(definition).expect("embedded Standard Model must be valid")
25    }
26
27    /// The Standard Model's QCD sector: six quark flavors, gluons, and gluon
28    /// ghosts. Keeps the Standard Model parameters and their default values.
29    pub fn qcd() -> Self {
30        Self::standard_model_sector("qcd", ModelParticle::is_qcd_charged)
31    }
32
33    /// The Standard Model's QED sector: photons and all charged fermions,
34    /// including quarks. Keeps the Standard Model parameters and their defaults.
35    pub fn qed() -> Self {
36        Self::standard_model_sector("qed", |particle| {
37            particle.pdg_code == 22 || (particle.is_fermion() && !particle.charge.is_zero())
38        })
39    }
40
41    /// The electroweak Standard Model, including quarks, Higgs, Goldstones,
42    /// and electroweak ghosts, with gluons and gluon ghosts removed.
43    pub fn electroweak() -> Self {
44        Self::standard_model_sector("electroweak", |particle| {
45            !particle.is_qcd_charged() || particle.is_fermion()
46        })
47    }
48
49    /// Strong and electromagnetic interactions of all quarks and charged
50    /// leptons, including gluon ghosts, with Standard Model parameters.
51    pub fn qcd_qed() -> Self {
52        Self::standard_model_sector("qcd_qed", |particle| {
53            particle.is_qcd_charged()
54                || particle.pdg_code == 22
55                || (particle.is_fermion() && !particle.charge.is_zero())
56        })
57    }
58
59    /// Pure SU(3) Yang–Mills theory: gluons and gluon ghosts, without quarks.
60    /// Preserves the Standard Model parameters and their default values.
61    pub fn yang_mills() -> Self {
62        Self::standard_model_sector("yang_mills", |particle| {
63            particle.is_qcd_charged() && !particle.is_fermion()
64        })
65    }
66
67    fn standard_model_sector(name: &str, keep_particle: impl Fn(&ModelParticle) -> bool) -> Self {
68        Self::with_parameter_display_transaction(|| {
69            Self::build_standard_model_sector(name, keep_particle)
70        })
71        .expect("filtered Standard Model sector must be valid")
72    }
73
74    fn build_standard_model_sector(
75        name: &str,
76        keep_particle: impl Fn(&ModelParticle) -> bool,
77    ) -> Result<Self, ModelError> {
78        let model = Self::standard_model();
79        let selected: BTreeSet<_> = model
80            .particles()
81            .iter()
82            .filter(|p| keep_particle(p))
83            .map(|p| p.name.as_str())
84            .collect();
85        let mut definition = model.definition();
86        definition.name = name.to_owned();
87        definition
88            .particles
89            .retain(|p| selected.contains(p.name.as_str()));
90        let pdgs: BTreeSet<_> = definition.particles.iter().map(|p| p.pdg_code).collect();
91        definition
92            .covariant_cut_multiplets
93            .retain(|_, members| members.iter().all(|pdg| pdgs.contains(pdg)));
94        let particles: BTreeSet<_> = definition.particles.iter().map(|p| &p.name).collect();
95        definition
96            .propagators
97            .retain(|propagator| particles.contains(&propagator.particle));
98        definition
99            .vertex_rules
100            .retain(|vertex| vertex.particles.iter().all(|p| particles.contains(p)));
101
102        let couplings: BTreeSet<_> = definition
103            .vertex_rules
104            .iter()
105            .flat_map(|vertex| vertex.couplings.iter().flatten().flatten())
106            .collect();
107        definition
108            .couplings
109            .retain(|coupling| couplings.contains(&coupling.name));
110        let lorentz_structures: BTreeSet<_> = definition
111            .vertex_rules
112            .iter()
113            .flat_map(|vertex| &vertex.lorentz_structures)
114            .collect();
115        definition
116            .lorentz_structures
117            .retain(|lorentz| lorentz_structures.contains(&lorentz.name));
118        let orders: BTreeSet<_> = definition
119            .couplings
120            .iter()
121            .flat_map(|coupling| coupling.orders.keys())
122            .collect();
123        definition
124            .orders
125            .retain(|order| orders.contains(&order.name));
126
127        // Keep the complete parameter definitions: expressions may depend on
128        // electroweak inputs even after electroweak particles have been removed.
129        Self::new(definition)
130    }
131
132    /// One real scalar `phi` with L_int = -g phi^3 / 3!.
133    /// External parameters `mass` and `g` default to one; the width is zero.
134    pub fn phi3() -> Self {
135        Self::real_scalar("phi3", 3, "g")
136    }
137
138    /// One real scalar `phi` with L_int = -lam phi^4 / 4!.
139    /// External parameters `mass` and `lam` default to one; the width is zero.
140    pub fn phi4() -> Self {
141        Self::real_scalar("phi4", 4, "lam")
142    }
143
144    /// One real scalar `phi` with L_int = -g phi^3 / 3! - lam phi^4 / 4!.
145    /// External parameters `mass`, `g`, and `lam` default to one; the width is zero.
146    pub fn phi_3_4() -> Self {
147        let mut definition = Self::phi3().definition();
148        let mut quartic = Self::phi4().definition();
149        definition.name = "phi_3_4".to_owned();
150        let mut coupling_parameter = quartic.parameters.pop().unwrap();
151        coupling_parameter.lhacode = Some(vec![3]);
152        definition.parameters.push(coupling_parameter);
153
154        quartic.lorentz_structures[0].name = "SCALAR4".to_owned();
155        quartic.couplings[0].name = "SCALAR4_COUPLING".to_owned();
156        quartic.vertex_rules[0].name = "V_SCALAR4".to_owned();
157        quartic.vertex_rules[0].lorentz_structures = vec!["SCALAR4".to_owned()];
158        quartic.vertex_rules[0].couplings = vec![vec![Some("SCALAR4_COUPLING".to_owned())]];
159        definition
160            .lorentz_structures
161            .extend(quartic.lorentz_structures);
162        definition.couplings.extend(quartic.couplings);
163        definition.vertex_rules.extend(quartic.vertex_rules);
164        Self::new(definition).expect("built-in cubic and quartic scalar model must be valid")
165    }
166
167    fn real_scalar(name: &str, valence: usize, coupling: &str) -> Self {
168        let parameters = [("ZERO", 0.0), ("mass", 1.0), (coupling, 1.0)]
169            .into_iter()
170            .enumerate()
171            .map(|(index, (name, value))| Parameter {
172                name: name.to_owned(),
173                texname: Some(
174                    match name {
175                        "ZERO" => "0",
176                        "mass" => "m",
177                        "lam" => r"\lambda",
178                        _ => name,
179                    }
180                    .to_owned(),
181                ),
182                typstname: Some(
183                    match name {
184                        "ZERO" => "0",
185                        "mass" => "m",
186                        "lam" => "lambda",
187                        _ => name,
188                    }
189                    .to_owned(),
190                ),
191                mathmlname: match name {
192                    "ZERO" => Some("<mn>0</mn>".to_owned()),
193                    "mass" => Some("<mi>m</mi>".to_owned()),
194                    "lam" => Some("<mi>λ</mi>".to_owned()),
195                    _ => None,
196                },
197                lhablock: (index != 0).then(|| "SCALAR".to_owned()),
198                lhacode: (index != 0).then(|| vec![index]),
199                nature: if index == 0 {
200                    ParameterNature::Internal
201                } else {
202                    ParameterNature::External
203                },
204                parameter_type: ParameterType::Real,
205                value: Some(ComplexValue::new(value, 0.0)),
206                expression: None,
207            })
208            .collect();
209        let definition = ModelDefinition {
210            covariant_cut_multiplets: Default::default(),
211            name: name.to_owned(),
212            restriction: None,
213            orders: vec![Order {
214                name: "SCALAR".to_owned(),
215                expansion_order: 99,
216                hierarchy: 1,
217            }],
218            parameters,
219            particles: vec![Particle {
220                pdg_code: 9000001,
221                name: "phi".to_owned(),
222                antiname: "phi".to_owned(),
223                spin: 1,
224                color: 1,
225                mass: "mass".to_owned(),
226                width: "ZERO".to_owned(),
227                chemical_potential: None,
228                texname: "\\phi".to_owned(),
229                antitexname: "\\phi".to_owned(),
230                typstname: Some("phi".to_owned()),
231                antitypstname: Some("phi".to_owned()),
232                charge: 0.into(),
233                ghost_number: 0,
234                lepton_number: 0,
235                y_charge: None,
236                y_charge_right: None,
237                propagating: true,
238                goldstone: false,
239                propagator: Some("phi_prop".to_owned()),
240            }],
241            propagators: vec![Propagator {
242                name: "phi_prop".to_owned(),
243                particle: "phi".to_owned(),
244                numerator: "1𝑖".to_owned(),
245                denominator: "(UFO::P(UFO::idx(1,1)))^2-UFO::mass^2".to_owned(),
246            }],
247            lorentz_structures: vec![LorentzStructure {
248                name: "SCALAR".to_owned(),
249                spins: vec![1; valence],
250                structure: "1".to_owned(),
251            }],
252            couplings: vec![Coupling {
253                name: "SCALAR_COUPLING".to_owned(),
254                expression: format!("-1𝑖*UFO::{coupling}"),
255                orders: BTreeMap::from([("SCALAR".to_owned(), 1)]),
256                value: Some(ComplexValue::new(0.0, -1.0)),
257            }],
258            vertex_rules: vec![VertexRule {
259                name: "V_SCALAR".to_owned(),
260                particles: vec!["phi".to_owned(); valence],
261                color_structures: vec!["1".to_owned()],
262                lorentz_structures: vec!["SCALAR".to_owned()],
263                couplings: vec![vec![Some("SCALAR_COUPLING".to_owned())]],
264            }],
265            functions: vec![],
266            form_factors: vec![],
267        };
268        Self::new(definition).expect("built-in real scalar model must be valid")
269    }
270
271    /// Scalar electrodynamics in Feynman gauge, with `a`, `phi+`, and `phi-`.
272    /// `mass` and `e` default to one, and `lam` defaults to zero. The scalar
273    /// potential is mass^2 |phi|^2 + lam |phi|^4 / 4; all widths vanish.
274    pub fn scalar_qed() -> Self {
275        let mut definition = Self::phi4().definition();
276        definition.name = "scalar_qed".to_owned();
277        let quartic = &mut definition.parameters[2];
278        quartic.value = Some(ComplexValue::new(0.0, 0.0));
279        let mut charge = quartic.clone();
280        charge.name = "e".to_owned();
281        charge.texname = Some("e".to_owned());
282        charge.typstname = Some("e".to_owned());
283        charge.mathmlname = Some("<mi>e</mi>".to_owned());
284        charge.lhacode = Some(vec![3]);
285        charge.value = Some(ComplexValue::new(1.0, 0.0));
286        definition.parameters.push(charge);
287        definition.couplings[0].value = Some(ComplexValue::new(0.0, 0.0));
288        definition.vertex_rules[0].particles =
289            ["phi-", "phi-", "phi+", "phi+"].map(str::to_owned).to_vec();
290
291        let scalar = definition.particles.pop().unwrap();
292        let propagator = definition.propagators.pop().unwrap();
293        for (name, antiname, sign) in [("phi+", "phi-", 1), ("phi-", "phi+", -1)] {
294            let propagator_name = format!("{name}_prop");
295            definition.particles.push(Particle {
296                name: name.to_owned(),
297                antiname: antiname.to_owned(),
298                pdg_code: sign * scalar.pdg_code,
299                charge: sign.into(),
300                texname: format!("\\phi^{{{}}}", if sign > 0 { "+" } else { "-" }),
301                antitexname: format!("\\phi^{{{}}}", if sign > 0 { "-" } else { "+" }),
302                typstname: Some(format!("phi^({})", if sign > 0 { "+" } else { "-" })),
303                antitypstname: Some(format!("phi^({})", if sign > 0 { "-" } else { "+" })),
304                propagator: Some(propagator_name.clone()),
305                ..scalar.clone()
306            });
307            definition.propagators.push(Propagator {
308                name: propagator_name,
309                particle: name.to_owned(),
310                ..propagator.clone()
311            });
312        }
313        definition.particles.push(Particle {
314            pdg_code: 22,
315            name: "a".to_owned(),
316            antiname: "a".to_owned(),
317            spin: 3,
318            mass: "ZERO".to_owned(),
319            texname: "\\gamma".to_owned(),
320            antitexname: "\\gamma".to_owned(),
321            typstname: Some("gamma".to_owned()),
322            antitypstname: Some("gamma".to_owned()),
323            propagator: Some("a_prop".to_owned()),
324            ..scalar
325        });
326        definition.propagators.push(Propagator {
327            name: "a_prop".to_owned(),
328            particle: "a".to_owned(),
329            numerator: "-1𝑖*UFO::Metric(UFO::idx(1,1),UFO::idx(1,2))".to_owned(),
330            denominator: "(UFO::P(UFO::idx(1,1)))^2".to_owned(),
331        });
332        definition.orders.push(Order {
333            name: "QED".to_owned(),
334            expansion_order: 99,
335            hierarchy: 1,
336        });
337        // All momenta are incoming. Match the SM's a G- G+ convention: the
338        // cubic rule is -i e (p_- - p_+) and the seagull is 2 i e^2 g(mu,nu).
339        for (name, particles, structure, expression, power, value) in [
340            (
341                "VSS",
342                vec!["a", "phi-", "phi+"],
343                "-1*UFO::P(UFO::idx(1,1),UFO::idx(1,3))+UFO::P(UFO::idx(1,1),UFO::idx(1,2))",
344                "-1𝑖*UFO::e",
345                1,
346                -1.0,
347            ),
348            (
349                "VVSS",
350                vec!["a", "a", "phi-", "phi+"],
351                "UFO::Metric(UFO::idx(1,1),UFO::idx(1,2))",
352                "2𝑖*UFO::e^2",
353                2,
354                2.0,
355            ),
356        ] {
357            definition.lorentz_structures.push(LorentzStructure {
358                name: name.to_owned(),
359                spins: particles
360                    .iter()
361                    .map(|p| if *p == "a" { 3 } else { 1 })
362                    .collect(),
363                structure: structure.to_owned(),
364            });
365            definition.couplings.push(Coupling {
366                name: name.to_owned(),
367                expression: expression.to_owned(),
368                orders: BTreeMap::from([("QED".to_owned(), power)]),
369                value: Some(ComplexValue::new(0.0, value)),
370            });
371            definition.vertex_rules.push(VertexRule {
372                name: name.to_owned(),
373                particles: particles.into_iter().map(str::to_owned).collect(),
374                color_structures: vec!["1".to_owned()],
375                lorentz_structures: vec![name.to_owned()],
376                couplings: vec![vec![Some(name.to_owned())]],
377            });
378        }
379        Self::new(definition).expect("built-in scalar QED model must be valid")
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::Model;
386    use symbolica::{atom::Atom, domains::rational::Rational};
387
388    #[test]
389    fn standard_model_quantum_numbers_and_antiparticles_are_exact() {
390        let model = Model::standard_model();
391        for (pdgs, charge, yl, yr, t3) in [
392            (
393                &[2, 4, 6][..],
394                Rational::from((2, 3)),
395                Rational::from((1, 3)),
396                Some(Rational::from((4, 3))),
397                Rational::from((1, 2)),
398            ),
399            (
400                &[1, 3, 5][..],
401                Rational::from((-1, 3)),
402                Rational::from((1, 3)),
403                Some(Rational::from((-2, 3))),
404                Rational::from((-1, 2)),
405            ),
406            (
407                &[11, 13, 15][..],
408                Rational::from(-1),
409                Rational::from(-1),
410                Some(Rational::from(-2)),
411                Rational::from((-1, 2)),
412            ),
413            (
414                &[12, 14, 16][..],
415                Rational::from(0),
416                Rational::from(-1),
417                None,
418                Rational::from((1, 2)),
419            ),
420        ] {
421            for &pdg in pdgs {
422                let p = model.particle_by_pdg(pdg).unwrap();
423                let anti = model.particle_by_id(p.antiparticle).unwrap();
424                assert_eq!(p.charge, charge);
425                assert_eq!(p.y_charge, Some(yl.clone()));
426                assert_eq!(p.y_charge_right, yr);
427                assert_eq!(p.weak_isospin(), Some(t3.clone()));
428                assert_eq!(
429                    p.weak_isospin_right(),
430                    yr.as_ref().map(|_| Rational::zero())
431                );
432                assert_eq!(anti.charge, -charge.clone());
433                assert_eq!(anti.y_charge, yr.as_ref().map(|y| -y.clone()));
434                assert_eq!(anti.y_charge_right, Some(-yl.clone()));
435                assert_eq!(anti.weak_isospin_right(), Some(-t3.clone()));
436                assert_eq!(p.mass, anti.mass);
437                assert_eq!(p.width, anti.width);
438                assert_eq!(p.spin, anti.spin);
439                assert_eq!(p.lepton_number, -anti.lepton_number);
440                assert_eq!(
441                    p.color,
442                    if p.color == 1 {
443                        anti.color
444                    } else {
445                        -anti.color
446                    }
447                );
448            }
449        }
450        for name in ["H", "G0"] {
451            assert!(model.particle(name).unwrap().weak_isospin().is_none());
452        }
453        for (name, sign) in [("G+", 1), ("G-", -1)] {
454            let p = model.particle(name).unwrap();
455            assert_eq!(p.y_charge, Some(sign.into()));
456            assert_eq!(p.weak_isospin(), Some(Rational::from((sign, 2))));
457            assert!(p.is_goldstone());
458        }
459        assert!(
460            model
461                .particle("ve")
462                .unwrap()
463                .symbolic_mass(&model)
464                .is_zero()
465        );
466        assert_eq!(
467            model.particle("c").unwrap().symbolic_mass(&model),
468            Atom::var(symbolica::symbol!("UFO::MC"))
469        );
470        for vertex in model.vertex_rules() {
471            let particles: Vec<_> = vertex
472                .particles
473                .iter()
474                .map(|&id| model.particle_by_id(id).unwrap())
475                .collect();
476            assert!(
477                particles
478                    .iter()
479                    .fold(Rational::zero(), |q, p| q + &p.charge)
480                    .is_zero(),
481                "{} violates charge conservation",
482                vertex.name
483            );
484            assert_eq!(
485                particles.iter().map(|p| p.ghost_number).sum::<i64>(),
486                0,
487                "{}",
488                vertex.name
489            );
490            assert_eq!(
491                particles.iter().map(|p| p.lepton_number).sum::<i64>(),
492                0,
493                "{}",
494                vertex.name
495            );
496        }
497    }
498
499    #[test]
500    fn quantum_number_json_preserves_exactness_and_unknowns() {
501        let model = Model::standard_model();
502        let mut json: serde_json::Value = serde_json::from_str(&model.to_json().unwrap()).unwrap();
503        let i = json["particles"]
504            .as_array()
505            .unwrap()
506            .iter()
507            .position(|p| p["name"] == "c")
508            .unwrap();
509        assert_eq!(json["particles"][i]["charge"], "2/3");
510        for (value, expected) in [
511            (2.0 / 3.0, "2/3"),
512            (-2.0 / 3.0, "-2/3"),
513            (1.0 / 11.0, "1/11"),
514            (1.0 / 1_000_000.0, "1/1000000"),
515            (4095.5, "8191/2"),
516            (4096.0, "4096"),
517            (-0.0, "0"),
518            (9_007_199_254_740_991.0, "9007199254740991"),
519        ] {
520            json["particles"][i]["charge"] = serde_json::json!(value);
521            let loaded = Model::from_json(&json.to_string()).unwrap();
522            assert_eq!(loaded.particle("c").unwrap().charge.to_string(), expected);
523        }
524        for invalid in [
525            serde_json::json!(0.6666666),
526            serde_json::json!((2.0_f64 / 3.0).next_up()),
527            serde_json::json!(1.0 / 1_000_001.0),
528            serde_json::json!(4096.5),
529            serde_json::json!(9_007_199_254_740_992.0),
530            serde_json::json!(1e30),
531            serde_json::json!("1/0"),
532            serde_json::json!("not a charge"),
533        ] {
534            json["particles"][i]["charge"] = invalid;
535            assert!(Model::from_json(&json.to_string()).is_err());
536        }
537        json["particles"][i]["charge"] =
538            serde_json::json!("123456789012345678901234567891/999999999999999999999999999999");
539        json["particles"][i]
540            .as_object_mut()
541            .unwrap()
542            .remove("y_charge");
543        json["particles"][i]
544            .as_object_mut()
545            .unwrap()
546            .remove("y_charge_right");
547        let model = Model::from_json(&json.to_string()).unwrap();
548        let p = model.particle("c").unwrap();
549        assert_eq!(
550            p.charge.to_string(),
551            "123456789012345678901234567891/999999999999999999999999999999"
552        );
553        assert!(p.weak_isospin().is_none());
554        assert!(p.weak_isospin_right().is_none());
555        let reloaded = Model::from_json(&model.to_json().unwrap()).unwrap();
556        assert_eq!(model.fingerprint(), reloaded.fingerprint());
557    }
558
559    #[test]
560    fn builtin_models_validate_and_round_trip() {
561        for (model, name, particles, vertices) in [
562            // The unrestricted SM retains the light-quark Yukawa interactions.
563            (Model::standard_model(), "sm", 43, 163),
564            (Model::qcd(), "qcd", 15, 9),
565            (Model::qed(), "qed", 19, 9),
566            (Model::electroweak(), "electroweak", 40, 154),
567            (Model::qcd_qed(), "qcd_qed", 22, 18),
568            (Model::yang_mills(), "yang_mills", 3, 3),
569            (Model::phi3(), "phi3", 1, 1),
570            (Model::phi4(), "phi4", 1, 1),
571            (Model::phi_3_4(), "phi_3_4", 1, 2),
572            (Model::scalar_qed(), "scalar_qed", 3, 3),
573        ] {
574            assert_eq!(model.name(), name);
575            assert_eq!(model.particles().len(), particles);
576            assert_eq!(model.vertex_rules().len(), vertices);
577            let reloaded = Model::from_json(&model.to_json().unwrap()).unwrap();
578            assert_eq!(reloaded.fingerprint(), model.fingerprint());
579        }
580    }
581
582    #[test]
583    fn compressed_standard_model_matches_the_source_fixture() {
584        let source = include_str!("../../tests/fixtures/sm.json");
585        let compressed = include_bytes!("../../data/sm.json.zlib");
586        assert!(compressed.len() < 8 * 1024);
587        let decoded = miniz_oxide::inflate::decompress_to_vec_zlib(compressed).unwrap();
588        assert_eq!(
589            serde_json::from_slice::<serde_json::Value>(&decoded).unwrap(),
590            serde_json::from_str::<serde_json::Value>(source).unwrap()
591        );
592        assert_eq!(
593            Model::standard_model().to_json().unwrap(),
594            Model::from_json(source).unwrap().to_json().unwrap()
595        );
596    }
597}