Skip to main content

feynkit_ufo/
lib.rs

1//! A thin adapter from Python's `ufo_model_loader` to [`feynkit_model`].
2//!
3//! The caller owns the Python interpreter. This crate neither initializes an
4//! interpreter nor changes Python logging, standard output, or standard error.
5
6#![forbid(unsafe_code)]
7
8use std::{
9    collections::BTreeMap,
10    ffi::CString,
11    path::{Path, PathBuf},
12};
13
14use feynkit_model::{
15    Model, ModelError, ParameterCard, ParameterMathMl, quantum_number_from_float,
16    quantum_number_from_json,
17};
18use pyo3::{
19    Py, PyAny, PyErr, Python,
20    prelude::PyAnyMethods,
21    types::{PyDict, PyDictMethods, PyFloat, PyModule},
22};
23use thiserror::Error;
24
25/// Options forwarded to `ufo_model_loader.commands.load_model`.
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct UfoLoadOptions {
28    pub restriction_name: Option<String>,
29    pub simplify_model: bool,
30    pub wrap_indices_in_lorentz_structures: bool,
31}
32
33impl Default for UfoLoadOptions {
34    fn default() -> Self {
35        Self {
36            restriction_name: None,
37            simplify_model: true,
38            wrap_indices_in_lorentz_structures: true,
39        }
40    }
41}
42
43/// Configured adapter for Python's `ufo_model_loader` package.
44#[derive(Clone, Debug, Default, PartialEq, Eq)]
45pub struct UfoLoader {
46    options: UfoLoadOptions,
47}
48
49impl UfoLoader {
50    pub fn new() -> Self {
51        Self::default()
52    }
53
54    pub fn with_options(options: UfoLoadOptions) -> Self {
55        Self { options }
56    }
57
58    pub fn options(&self) -> &UfoLoadOptions {
59        &self.options
60    }
61
62    pub fn restriction_name(mut self, restriction_name: impl Into<String>) -> Self {
63        self.options.restriction_name = Some(restriction_name.into());
64        self
65    }
66
67    pub fn simplify_model(mut self, simplify_model: bool) -> Self {
68        self.options.simplify_model = simplify_model;
69        self
70    }
71
72    pub fn wrap_indices_in_lorentz_structures(mut self, wrap: bool) -> Self {
73        self.options.wrap_indices_in_lorentz_structures = wrap;
74        self
75    }
76
77    /// Load a UFO model using an already-attached Python interpreter.
78    pub fn load(
79        &self,
80        py: Python<'_>,
81        path: impl AsRef<Path>,
82    ) -> Result<LoadedModel, UfoLoadError> {
83        Model::with_parameter_display_transaction(|| load_model(py, path.as_ref(), &self.options))
84    }
85}
86
87/// A model and the parameter values returned by the UFO loader.
88#[derive(Clone, Debug)]
89pub struct LoadedModel {
90    pub model: Model,
91    pub parameters: ParameterCard,
92    pub diagnostics: UfoLoadDiagnostics,
93}
94
95/// Requested loader inputs and counts from the normalized output.
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub struct UfoLoadDiagnostics {
98    pub source: PathBuf,
99    pub options: UfoLoadOptions,
100    pub order_count: usize,
101    pub model_parameter_count: usize,
102    pub particle_count: usize,
103    pub propagator_count: usize,
104    pub lorentz_structure_count: usize,
105    pub coupling_count: usize,
106    pub vertex_rule_count: usize,
107    pub function_count: usize,
108    pub form_factor_count: usize,
109    pub parameter_value_count: usize,
110}
111
112/// Errors produced while loading a UFO model.
113#[derive(Debug, Error)]
114pub enum UfoLoadError {
115    #[error("UFO model path '{}' is not valid UTF-8", path.display())]
116    NonUtf8Path { path: PathBuf },
117    #[error("could not import 'ufo_model_loader.commands': {source}")]
118    Import {
119        #[source]
120        source: PyErr,
121    },
122    #[error("could not resolve 'ufo_model_loader.commands.load_model': {source}")]
123    ResolveLoader {
124        #[source]
125        source: PyErr,
126    },
127    #[error("could not construct arguments for 'ufo_model_loader.commands.load_model': {source}")]
128    Arguments {
129        #[source]
130        source: PyErr,
131    },
132    #[error("'ufo_model_loader.commands.load_model' failed: {source}")]
133    Load {
134        #[source]
135        source: PyErr,
136    },
137    #[error("invalid output from 'ufo_model_loader.commands.load_model': {source}")]
138    Output {
139        #[source]
140        source: PyErr,
141    },
142    #[error(
143        "unsupported UFO float {value} for particle '{particle}', attribute '{attribute}'. Supply an exact fraction string such as '2/3'."
144    )]
145    QuantumNumber {
146        particle: String,
147        attribute: String,
148        value: f64,
149    },
150    #[error("invalid model JSON field '{field}' for particle '{particle}': {source}")]
151    JsonQuantumNumber {
152        particle: String,
153        field: &'static str,
154        #[source]
155        source: serde_json::Error,
156    },
157    #[error("could not deserialize the loaded model: {source}")]
158    ModelJson {
159        #[source]
160        source: ModelError,
161    },
162    #[error("could not deserialize the loaded parameter card: {source}")]
163    ParameterCardJson {
164        #[source]
165        source: ModelError,
166    },
167}
168
169type DisplayNames = (Option<String>, Option<String>, Option<String>);
170
171// The Python loader handles restriction discovery and simplification at the original
172// path. Keep the model JSON's charge tokens so it cannot round floats into strings.
173type JsonParticleNumbers = BTreeMap<String, [String; 3]>;
174
175fn json_particle_metadata(source: JsonParticleNumbers) -> Result<serde_json::Value, UfoLoadError> {
176    let mut particles = serde_json::Map::new();
177    for (particle, tokens) in source {
178        let mut numbers = serde_json::Map::new();
179        for (field, token) in ["charge", "y_charge", "y_charge_right"]
180            .into_iter()
181            .zip(tokens)
182        {
183            let value = if field != "charge" && token == "null" {
184                serde_json::Value::Null
185            } else {
186                let number = quantum_number_from_json(&token).map_err(|source| {
187                    UfoLoadError::JsonQuantumNumber {
188                        particle: particle.clone(),
189                        field,
190                        source,
191                    }
192                })?;
193                serde_json::Value::String(number.to_string())
194            };
195            numbers.insert(field.to_owned(), value);
196        }
197        particles.insert(particle, serde_json::Value::Object(numbers));
198    }
199    Ok(serde_json::json!({"particles": particles}))
200}
201
202fn load_model(
203    py: Python<'_>,
204    path: &Path,
205    options: &UfoLoadOptions,
206) -> Result<LoadedModel, UfoLoadError> {
207    let input_model_path = path.to_str().ok_or_else(|| UfoLoadError::NonUtf8Path {
208        path: path.to_path_buf(),
209    })?;
210    // The Python loader creates symbols while parsing parameter expressions.
211    // Declare their printers first, before even a forward reference can do so.
212    let metadata_source = CString::new(include_str!("model_metadata.py")).unwrap();
213    let (labels, source_model, json_particles) = (|| {
214        PyModule::from_code(
215            py,
216            &metadata_source,
217            c"model_metadata.py",
218            c"_model_metadata",
219        )?
220        .getattr("model_metadata")?
221        .call1((input_model_path,))?
222        .extract::<(
223            Vec<(String, DisplayNames)>,
224            Option<Py<PyAny>>,
225            Option<JsonParticleNumbers>,
226        )>()
227    })()
228    .map_err(|source| UfoLoadError::Load { source })?;
229    // Validate the source quantum numbers before publishing parameter labels.
230    // Python's own model serialization can reject a non-finite float first.
231    let metadata = (|| -> Result<Result<Option<String>, UfoLoadError>, PyErr> {
232        let Some(module) = source_model.as_ref() else {
233            return Ok(Ok(None));
234        };
235        let module = module.bind(py);
236        let metadata = PyDict::new(py);
237        if module.hasattr("covariant_cut_multiplets")? {
238            metadata.set_item(
239                "covariant_cut_multiplets",
240                module.getattr("covariant_cut_multiplets")?,
241            )?;
242        }
243        let particles = PyDict::new(py);
244        if module.hasattr("all_particles")? {
245            let fraction = py.import("fractions")?.getattr("Fraction")?;
246            for particle in module.getattr("all_particles")?.try_iter()? {
247                let particle = particle?;
248                let numbers = PyDict::new(py);
249                if particle.hasattr("chemical_potential")?
250                    && !particle.getattr("chemical_potential")?.is_none()
251                {
252                    numbers.set_item(
253                        "chemical_potential",
254                        particle.getattr("chemical_potential")?.getattr("name")?,
255                    )?;
256                }
257                for field in ["typstname", "antitypstname"] {
258                    if particle.hasattr(field)? {
259                        numbers.set_item(field, particle.getattr(field)?)?;
260                    }
261                }
262                for (field, attribute) in [
263                    ("charge", "charge"),
264                    ("y_charge", "Y"),
265                    ("y_charge_right", "YRight"),
266                ] {
267                    let attribute = if field == "charge" && particle.hasattr("charge_exact")? {
268                        "charge_exact"
269                    } else {
270                        attribute
271                    };
272                    if particle.hasattr(attribute)? && !particle.getattr(attribute)?.is_none() {
273                        // Integers and fraction strings stay exact; never guess a
274                        // charge from PDG codes. A float such as `charge = 2/3` is
275                        // the fraction with denominator at most 10^6 that rounds to
276                        // it. Such fractions lie at least 1e-12 apart, more than the
277                        // float spacing below 4096, so at most one qualifies there.
278                        let value = particle.getattr(attribute)?;
279                        let exact = if value.is_instance_of::<PyFloat>() {
280                            let float: f64 = value.extract()?;
281                            let Some(closest) = quantum_number_from_float(float) else {
282                                return Ok(Err(UfoLoadError::QuantumNumber {
283                                    particle: particle.getattr("name")?.extract()?,
284                                    attribute: attribute.to_owned(),
285                                    value: float,
286                                }));
287                            };
288                            closest.to_string()
289                        } else {
290                            fraction
291                                .call1((value.str()?,))?
292                                .str()?
293                                .extract::<String>()?
294                        };
295                        numbers.set_item(field, exact)?;
296                    } else {
297                        numbers.set_item(field, py.None())?;
298                    }
299                }
300                particles.set_item(particle.getattr("name")?, numbers)?;
301            }
302        }
303        metadata.set_item("particles", particles)?;
304        py.import("json")?
305            .call_method1("dumps", (metadata,))?
306            .extract()
307            .map(|json| Ok(Some(json)))
308    })()
309    .map_err(|source| UfoLoadError::Output { source })??;
310
311    let metadata = match json_particles {
312        Some(particles) => json_particle_metadata(particles)?,
313        None => serde_json::from_str(metadata.as_deref().unwrap_or("{}")).map_err(
314            |source: serde_json::Error| UfoLoadError::ModelJson {
315                source: source.into(),
316            },
317        )?,
318    };
319
320    let labels: BTreeMap<_, _> = labels.into_iter().collect();
321    let mathml_labels = labels
322        .iter()
323        .map(|(name, (_, _, mathml))| ParameterMathMl::for_parameter(name, mathml.as_deref()))
324        .collect::<Result<Vec<_>, _>>()
325        .map_err(|source| UfoLoadError::ModelJson { source })?;
326    for ((name, (texname, typstname, _)), mathml) in labels.iter().zip(&mathml_labels) {
327        Model::register_parameter_display(
328            name,
329            texname.as_deref(),
330            typstname.as_deref(),
331            mathml.as_ref(),
332        )
333        .map_err(|source| UfoLoadError::ModelJson { source })?;
334    }
335    let commands = PyModule::import(py, "ufo_model_loader.commands")
336        .map_err(|source| UfoLoadError::Import { source })?;
337    let loader = commands
338        .getattr("load_model")
339        .map_err(|source| UfoLoadError::ResolveLoader { source })?;
340
341    // kwargs: input_model_path, restriction_name, simplify_model,
342    // wrap_indices_in_lorentz_structures
343    let kwargs = PyDict::new(py);
344    kwargs
345        .set_item("input_model_path", input_model_path)
346        .map_err(|source| UfoLoadError::Arguments { source })?;
347    match options.restriction_name.as_deref() {
348        Some(name) => kwargs.set_item("restriction_name", name),
349        None => kwargs.set_item("restriction_name", py.None()),
350    }
351    .and_then(|_| kwargs.set_item("simplify_model", options.simplify_model))
352    .and_then(|_| {
353        kwargs.set_item(
354            "wrap_indices_in_lorentz_structures",
355            options.wrap_indices_in_lorentz_structures,
356        )
357    })
358    .map_err(|source| UfoLoadError::Arguments { source })?;
359
360    // Expect a 2-tuple: (model, input_param_card).
361    let output = loader
362        .call((), Some(&kwargs))
363        .map_err(|source| UfoLoadError::Load { source })?;
364    let (py_model, py_card): (Py<PyAny>, Py<PyAny>) = output
365        .extract()
366        .map_err(|source| UfoLoadError::Output { source })?;
367
368    // to_json() -> String
369    let mut model_json = to_json(py, &py_model)?;
370    let card_json = to_json(py, &py_card)?;
371
372    let enrich = || -> Result<String, serde_json::Error> {
373        let mut serialized: serde_json::Value = serde_json::from_str(&model_json)?;
374        if let Some(declaration) = metadata.get("covariant_cut_multiplets") {
375            serialized["covariant_cut_multiplets"] = declaration.clone();
376        }
377        if let Some(particles) = serialized["particles"].as_array_mut() {
378            for particle in particles {
379                if let Some(numbers) =
380                    metadata["particles"].get(particle["name"].as_str().unwrap_or_default())
381                {
382                    for field in [
383                        "charge",
384                        "y_charge",
385                        "y_charge_right",
386                        "typstname",
387                        "antitypstname",
388                        "chemical_potential",
389                    ] {
390                        if let Some(value) = numbers.get(field) {
391                            particle[field] = value.clone();
392                        }
393                    }
394                }
395            }
396        }
397        if let Some(parameters) = serialized["parameters"].as_array_mut() {
398            for parameter in parameters {
399                if let Some((texname, typstname, mathmlname)) =
400                    labels.get(parameter["name"].as_str().unwrap_or_default())
401                {
402                    parameter["texname"] = serde_json::to_value(texname)?;
403                    parameter["typstname"] = serde_json::to_value(typstname)?;
404                    parameter["mathmlname"] = serde_json::to_value(mathmlname)?;
405                }
406            }
407        }
408        serde_json::to_string(&serialized)
409    };
410    model_json = enrich().map_err(|source| UfoLoadError::ModelJson {
411        source: source.into(),
412    })?;
413
414    // Deserialize into the standalone Rust types.
415    let model =
416        Model::from_json(&model_json).map_err(|source| UfoLoadError::ModelJson { source })?;
417    let parameters = ParameterCard::from_json(&card_json)
418        .map_err(|source| UfoLoadError::ParameterCardJson { source })?;
419
420    let diagnostics = UfoLoadDiagnostics {
421        source: path.to_path_buf(),
422        options: options.clone(),
423        order_count: model.orders().len(),
424        model_parameter_count: model.parameters().len(),
425        particle_count: model.particles().len(),
426        propagator_count: model.propagators().len(),
427        lorentz_structure_count: model.lorentz_structures().len(),
428        coupling_count: model.couplings().len(),
429        vertex_rule_count: model.vertex_rules().len(),
430        function_count: model.functions().len(),
431        form_factor_count: model.form_factors().len(),
432        parameter_value_count: parameters.len(),
433    };
434
435    Ok(LoadedModel {
436        model,
437        parameters,
438        diagnostics,
439    })
440}
441
442fn to_json(py: Python<'_>, value: &Py<PyAny>) -> Result<String, UfoLoadError> {
443    value
444        .call_method0(py, "to_json")
445        .and_then(|json| json.extract(py))
446        .map_err(|source| UfoLoadError::Output { source })
447}
448
449#[cfg(test)]
450mod tests {
451    use std::ffi::CString;
452
453    use pyo3::types::{PyDict, PyModule};
454
455    use super::*;
456
457    const MODEL_JSON: &str = r#"{
458        "name":"scalar","restriction":null,
459        "orders":[{"name":"QED","expansion_order":99,"hierarchy":1}],
460        "parameters":[
461            {"name":"ZERO","lhablock":null,"lhacode":null,"nature":"internal","parameter_type":"real","value":[0.0,0.0],"expression":null},
462            {"name":"mass","lhablock":"MASS","lhacode":[1],"nature":"external","parameter_type":"real","value":[1.0,0.0],"expression":null}
463        ],
464        "particles":[{"pdg_code":1,"name":"s","antiname":"s","spin":1,"color":1,"mass":"mass","width":"ZERO","texname":"s","antitexname":"s","charge":0.0,"ghost_number":0,"lepton_number":0,"y_charge":0}],
465        "propagators":[],"lorentz_structures":[],"couplings":[],"vertex_rules":[]
466    }"#;
467
468    #[test]
469    fn defaults_match_the_existing_loader_contract() {
470        assert_eq!(UfoLoader::new(), UfoLoader::default());
471        assert_eq!(
472            UfoLoader::with_options(UfoLoadOptions::default()).options(),
473            &UfoLoadOptions {
474                restriction_name: None,
475                simplify_model: true,
476                wrap_indices_in_lorentz_structures: true,
477            }
478        );
479    }
480
481    #[test]
482    fn forwards_options_and_deserializes_json() {
483        Python::initialize();
484        Python::attach(|py| {
485            let temporary = PyModule::import(py, "tempfile")
486                .unwrap()
487                .getattr("TemporaryDirectory")
488                .unwrap()
489                .call0()
490                .unwrap();
491            let directory = temporary
492                .getattr("name")
493                .unwrap()
494                .extract::<PathBuf>()
495                .unwrap();
496            let model_path = directory.join("scalar.json");
497            std::fs::write(&model_path, MODEL_JSON).unwrap();
498            let code = format!(
499                r#"
500import contextlib
501import sys
502import types
503
504MODEL_JSON = {MODEL_JSON:?}
505CARD_JSON = '{{"mass":[2.5,0.0]}}'
506seen = {{}}
507
508class JsonValue:
509    def __init__(self, value):
510        self.value = value
511
512    def to_json(self):
513        return self.value
514
515def load_model(**kwargs):
516    seen.update(kwargs)
517    return JsonValue(MODEL_JSON), JsonValue(CARD_JSON)
518
519package = types.ModuleType("ufo_model_loader")
520package.__path__ = []
521common = types.ModuleType("ufo_model_loader.common")
522common.DATA_PATH = ""
523raw = types.ModuleType("ufo_model_loader.raw")
524
525@contextlib.contextmanager
526def imported_ufo_module(source):
527    yield sys.modules[source.name]
528
529raw.imported_ufo_module = imported_ufo_module
530commands = types.ModuleType("ufo_model_loader.commands")
531commands.load_model = load_model
532commands.seen = seen
533package.commands = commands
534package.common = common
535package.raw = raw
536sys.modules["ufo_model_loader"] = package
537sys.modules["ufo_model_loader.commands"] = commands
538sys.modules["ufo_model_loader.common"] = common
539sys.modules["ufo_model_loader.raw"] = raw
540"#
541            );
542            PyModule::from_code(
543                py,
544                CString::new(code).unwrap().as_c_str(),
545                c"feynkit_ufo_test.py",
546                c"feynkit_ufo_test",
547            )
548            .unwrap();
549
550            let loader = UfoLoader::new()
551                .restriction_name("massless")
552                .simplify_model(false)
553                .wrap_indices_in_lorentz_structures(false);
554            let loaded = loader.load(py, &model_path).unwrap();
555            assert_eq!(loaded.model.name(), "scalar");
556            assert_eq!(loaded.parameters["mass"].re, 2.5);
557            assert!(loaded.model.particle("s").unwrap().is_propagating());
558            assert!(loaded.model.functions().is_empty());
559            assert!(loaded.model.form_factors().is_empty());
560            assert_eq!(
561                loaded.diagnostics,
562                UfoLoadDiagnostics {
563                    source: model_path.clone(),
564                    options: loader.options().clone(),
565                    order_count: 1,
566                    model_parameter_count: 2,
567                    particle_count: 1,
568                    propagator_count: 0,
569                    lorentz_structure_count: 0,
570                    coupling_count: 0,
571                    vertex_rule_count: 0,
572                    function_count: 0,
573                    form_factor_count: 0,
574                    parameter_value_count: 1,
575                }
576            );
577
578            let commands = PyModule::import(py, "ufo_model_loader.commands").unwrap();
579            let seen = commands
580                .getattr("seen")
581                .unwrap()
582                .cast_into::<PyDict>()
583                .unwrap();
584            assert_eq!(
585                seen.get_item("input_model_path")
586                    .unwrap()
587                    .unwrap()
588                    .extract::<String>()
589                    .unwrap(),
590                model_path.to_str().unwrap()
591            );
592            assert_eq!(
593                seen.get_item("restriction_name")
594                    .unwrap()
595                    .unwrap()
596                    .extract::<String>()
597                    .unwrap(),
598                "massless"
599            );
600            assert!(
601                !seen
602                    .get_item("simplify_model")
603                    .unwrap()
604                    .unwrap()
605                    .extract::<bool>()
606                    .unwrap()
607            );
608            assert!(
609                !seen
610                    .get_item("wrap_indices_in_lorentz_structures")
611                    .unwrap()
612                    .unwrap()
613                    .extract::<bool>()
614                    .unwrap()
615            );
616
617            // The upstream loader can normalize a numeric JSON charge into a long
618            // decimal fraction. Use the original three scalars with the direct model rules.
619            let mut file_model: serde_json::Value = serde_json::from_str(MODEL_JSON).unwrap();
620            file_model["particles"][0]["charge"] = (2.0 / 3.0).into();
621            file_model["particles"][0]["y_charge"] = (1.0 / 3.0).into();
622            file_model["particles"][0]["y_charge_right"] = serde_json::Value::Null;
623            std::fs::write(&model_path, file_model.to_string()).unwrap();
624            let file = loader.load(py, &model_path).unwrap();
625            let s = file.model.particle("s").unwrap();
626            assert_eq!(s.charge.to_string(), "2/3");
627            assert_eq!(s.y_charge.as_ref().unwrap().to_string(), "1/3");
628            assert!(s.y_charge_right.is_none());
629            for (spelling, expected) in [
630                ("0.5", "1/2"),
631                ("1e-3", "1/1000"),
632                ("1/1000001", "1/1000001"),
633            ] {
634                file_model["particles"][0]["charge"] = spelling.into();
635                std::fs::write(&model_path, file_model.to_string()).unwrap();
636                let file = loader.load(py, &model_path).unwrap();
637                assert_eq!(
638                    file.model.particle("s").unwrap().charge.to_string(),
639                    expected
640                );
641            }
642            file_model["particles"][0]["charge"] = "1/-3".into();
643            std::fs::write(&model_path, file_model.to_string()).unwrap();
644            let error = loader.load(py, &model_path).unwrap_err();
645            assert!(
646                error
647                    .to_string()
648                    .contains("field 'charge' for particle 's'")
649            );
650            file_model["particles"][0]["charge"] = 0.6666666.into();
651            std::fs::write(&model_path, file_model.to_string()).unwrap();
652            assert!(matches!(
653                loader.load(py, &model_path),
654                Err(UfoLoadError::JsonQuantumNumber { particle, field: "charge", .. })
655                    if particle == "s"
656            ));
657
658            let modules = PyModule::import(py, "sys")
659                .unwrap()
660                .getattr("modules")
661                .unwrap()
662                .cast_into::<PyDict>()
663                .unwrap();
664            let source = PyModule::from_code(
665                py,
666                c"from types import SimpleNamespace\nall_parameters = [SimpleNamespace(name='ZERO'), SimpleNamespace(name='mass', mathmlname='<msub><mi>m</mi><mi>s</mi></msub>')]\nall_particles = [SimpleNamespace(name='s', charge=0.6666666666666666, charge_exact='2/3', Y='1/3', YRight='4/3')]",
667                c"scalar.py", c"scalar",
668            ).unwrap();
669            modules.set_item("scalar", &source).unwrap();
670            let model_directory = directory.join("scalar");
671            std::fs::create_dir(&model_directory).unwrap();
672            let exact = loader.load(py, &model_directory).unwrap();
673            assert_eq!(
674                exact
675                    .model
676                    .parameter("mass")
677                    .unwrap()
678                    .mathmlname
679                    .as_ref()
680                    .unwrap()
681                    .as_str(),
682                "<msub><mi>m</mi><mi>s</mi></msub>"
683            );
684            assert!(exact.model.parameter("ZERO").unwrap().mathmlname.is_none());
685            let particle = exact.model.particle("s").unwrap();
686            assert_eq!(particle.charge.to_string(), "2/3");
687            assert_eq!(particle.y_charge.as_ref().unwrap().to_string(), "1/3");
688            assert_eq!(particle.y_charge_right.as_ref().unwrap().to_string(), "4/3");
689            let particle = source
690                .getattr("all_particles")
691                .unwrap()
692                .get_item(0)
693                .unwrap();
694            particle.delattr("Y").unwrap();
695            particle.setattr("YRight", py.None()).unwrap();
696            let unknown = loader.load(py, &model_directory).unwrap();
697            assert!(
698                unknown
699                    .model
700                    .particle("s")
701                    .unwrap()
702                    .weak_isospin()
703                    .is_none()
704            );
705            assert!(
706                unknown
707                    .model
708                    .particle("s")
709                    .unwrap()
710                    .weak_isospin_right()
711                    .is_none()
712            );
713            // A stock UFO model has only floats, e.g. `charge = 2/3`, `Y = 1/3`.
714            particle.delattr("charge_exact").unwrap();
715            particle.setattr("Y", 1.0 / 3.0).unwrap();
716            particle.setattr("YRight", 4.0 / 3.0).unwrap();
717            let float = loader.load(py, &model_directory).unwrap();
718            let particle_s = float.model.particle("s").unwrap();
719            assert_eq!(particle_s.charge.to_string(), "2/3");
720            assert_eq!(particle_s.y_charge.as_ref().unwrap().to_string(), "1/3");
721            assert_eq!(
722                particle_s.y_charge_right.as_ref().unwrap().to_string(),
723                "4/3"
724            );
725            assert_eq!(particle_s.weak_isospin().unwrap().to_string(), "1/2");
726            assert_eq!(particle_s.weak_isospin_right().unwrap().to_string(), "0");
727            // Invalid floats must fail at the source with the particle and attribute.
728            seen.clear();
729            for value in [0.6666666, 4096.5, f64::NAN, f64::INFINITY] {
730                particle.setattr("YRight", value).unwrap();
731                let error = loader.load(py, &model_directory).unwrap_err();
732                assert!(
733                    matches!(
734                        &error,
735                        UfoLoadError::QuantumNumber { particle, attribute, .. }
736                            if particle == "s" && attribute == "YRight"
737                    ),
738                    "{error}"
739                );
740            }
741            assert!(seen.is_empty(), "invalid source reached the Python loader");
742            modules.del_item("scalar").unwrap();
743            modules.del_item("ufo_model_loader.commands").unwrap();
744            modules.del_item("ufo_model_loader.raw").unwrap();
745            modules.del_item("ufo_model_loader.common").unwrap();
746            modules.del_item("ufo_model_loader").unwrap();
747            temporary.call_method0("cleanup").unwrap();
748        });
749    }
750}