laddu-physics 0.20.0

Amplitude analysis tools for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::{
    LadduPhysicsError, LadduPhysicsResult,
    quantum::{J, L, M, Parity, Statistics},
};

/// An external identifier associated with a physical particle species.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum ExternalId {
    /// A numeric identifier, such as a PDG code.
    Code {
        /// Identifier value.
        value: i64,
    },
    /// A textual identifier.
    Label {
        /// Identifier value.
        value: String,
    },
}

impl From<&str> for ExternalId {
    fn from(value: &str) -> Self {
        Self::label(value)
    }
}
impl From<String> for ExternalId {
    fn from(value: String) -> Self {
        Self::label(value)
    }
}
impl From<&String> for ExternalId {
    fn from(value: &String) -> Self {
        Self::label(value)
    }
}
impl From<i64> for ExternalId {
    fn from(value: i64) -> Self {
        Self::code(value)
    }
}

impl ExternalId {
    /// Construct a numeric identifier.
    pub fn code(value: i64) -> Self {
        Self::Code { value }
    }

    /// Construct a textual identifier in an arbitrary namespace.
    pub fn label(value: impl Into<String>) -> Self {
        Self::Label {
            value: value.into(),
        }
    }

    /// Return the numeric value, if this is a numeric identifier.
    pub fn code_value(&self) -> Option<i64> {
        match self {
            Self::Code { value, .. } => Some(*value),
            Self::Label { .. } => None,
        }
    }

    /// Return the textual value, if this is a textual identifier.
    pub fn label_value(&self) -> Option<&str> {
        match self {
            Self::Label { value, .. } => Some(value),
            Self::Code { .. } => None,
        }
    }
}

/// A validated spin state with spin and projection stored as doubled quantum numbers.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct SpinState {
    spin: J,
    projection: M,
}

impl SpinState {
    /// Construct a spin state after validating projection bounds and parity.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when `projection` is outside the spin
    /// range or has incompatible integer/half-integer parity.
    pub fn new(spin: J, projection: M) -> LadduPhysicsResult<Self> {
        validate_projection(spin, projection)?;
        Ok(Self { spin, projection })
    }

    /// Return the spin quantum number.
    pub const fn spin(self) -> J {
        self.spin
    }

    /// Return the spin projection quantum number.
    pub const fn projection(self) -> M {
        self.projection
    }
}

/// An isospin state with optional projection.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct Isospin {
    /// The total isospin of the state.
    pub isospin: J,
    /// The isospin projection of the state.
    pub projection: Option<M>,
}

impl Isospin {
    /// Construct a new isospin state from the given total isospin and optional projection.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when the projection is outside the
    /// isospin range or has incompatible integer/half-integer parity.
    pub fn new(isospin: J, projection: Option<M>) -> LadduPhysicsResult<Self> {
        if let Some(projection) = projection {
            validate_projection(isospin, projection)?;
        }
        Ok(Self {
            isospin,
            projection,
        })
    }

    /// The total isospin of the state.
    pub fn isospin(self) -> J {
        self.isospin
    }
    /// The isospin projection of the state.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the
    /// projection is unknown.
    pub fn projection(self) -> LadduPhysicsResult<M> {
        self.projection
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "isospin.projection",
            })
    }
}

impl From<J> for Isospin {
    fn from(value: J) -> Self {
        Self {
            isospin: value,
            projection: None,
        }
    }
}

/// The set of properties which define the quantum state of a particle.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ParticleProperties {
    /// The name of the particle, if known.
    pub name: Option<String>,
    /// The species of the particle, if known (used to compare to [`ParticleProperties::antiparticle_species`]).
    pub species: Option<String>,
    /// The species of the particle's antiparticle, if known (used to compare to [`ParticleProperties::species`]).
    pub antiparticle_species: Option<String>,
    /// Whether the particle is its own antiparticle.
    pub self_conjugate: Option<bool>,
    /// The spin of the particle, if known.
    pub spin: Option<J>,
    /// The intrinsic parity of the particle, if known.
    pub parity: Option<Parity>,
    /// The intrinsic C-parity of the particle, if known or applicable.
    pub c_parity: Option<Parity>,
    /// The intrinsic G-parity of the particle, if known or applicable.
    pub g_parity: Option<Parity>,
    /// The electric charge of the particle, if known.
    pub charge: Option<i32>,
    /// The isospin of the particle, if known.
    pub isospin: Option<Isospin>,
    /// The total strangeness of the particle, if known.
    pub strangeness: Option<i32>,
    /// The total charm of the particle, if known.
    pub charm: Option<i32>,
    /// The total bottomness of the particle, if known.
    pub bottomness: Option<i32>,
    /// The total topness of the particle, if known.
    pub topness: Option<i32>,
    /// The total baryon number of the particle, if known.
    pub baryon_number: Option<i32>,
    /// The electron lepton number of the particle, if known.
    pub electron_lepton_number: Option<i32>,
    /// The muon lepton number of the particle, if known.
    pub muon_lepton_number: Option<i32>,
    /// The tau lepton number of the particle, if known.
    pub tau_lepton_number: Option<i32>,
    /// The particle's statistical nature, if known.
    pub statistics: Option<Statistics>,
    /// The nominal particle mass, if known.
    pub mass: Option<f64>,
    /// External identifiers for this particle.
    pub ids: IndexMap<String, ExternalId>,
}

impl ParticleProperties {
    /// Get the particle's name
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the name is
    /// unknown.
    pub fn name(&self) -> LadduPhysicsResult<String> {
        self.name
            .clone()
            .ok_or(LadduPhysicsError::MissingParticleProperty { property: "name" })
            .clone()
    }
    /// Get the particle's species
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the species
    /// is unknown.
    pub fn species(&self) -> LadduPhysicsResult<String> {
        self.species
            .clone()
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "species",
            })
            .clone()
    }
    /// Get the particle's antiparticle species
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the
    /// antiparticle species is unknown.
    pub fn antiparticle_species(&self) -> LadduPhysicsResult<String> {
        self.antiparticle_species
            .clone()
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "antiparticle_species",
            })
            .clone()
    }
    /// Get the particle's self-conjugate status
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the
    /// self-conjugate status is unknown.
    pub fn self_conjugate(&self) -> LadduPhysicsResult<bool> {
        self.self_conjugate
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "self_conjugate",
            })
            .clone()
    }
    /// Get the particle's spin
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the spin is
    /// unknown.
    pub fn spin(&self) -> LadduPhysicsResult<J> {
        self.spin
            .ok_or(LadduPhysicsError::MissingParticleProperty { property: "spin" })
            .clone()
    }
    /// Get the particle's intrinsic parity
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when parity is
    /// unknown.
    pub fn parity(&self) -> LadduPhysicsResult<Parity> {
        self.parity
            .ok_or(LadduPhysicsError::MissingParticleProperty { property: "parity" })
            .clone()
    }
    /// Get the particle's intrinsic C-parity
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when C-parity is
    /// unknown.
    pub fn c_parity(&self) -> LadduPhysicsResult<Parity> {
        self.c_parity
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "c_parity",
            })
            .clone()
    }
    /// Get the particle's intrinsic G-parity
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when G-parity is
    /// unknown.
    pub fn g_parity(&self) -> LadduPhysicsResult<Parity> {
        self.g_parity
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "g_parity",
            })
            .clone()
    }
    /// Get the particle's electric charge
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when charge is
    /// unknown.
    pub fn charge(&self) -> LadduPhysicsResult<i32> {
        self.charge
            .ok_or(LadduPhysicsError::MissingParticleProperty { property: "charge" })
            .clone()
    }
    /// Get the particle's isospin
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when isospin is
    /// unknown.
    pub fn isospin(&self) -> LadduPhysicsResult<Isospin> {
        self.isospin
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "isospin",
            })
            .clone()
    }
    /// Get the particle's strangeness
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when strangeness
    /// is unknown.
    pub fn strangeness(&self) -> LadduPhysicsResult<i32> {
        self.strangeness
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "strangeness",
            })
            .clone()
    }
    /// Get the particle's charm
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when charm is
    /// unknown.
    pub fn charm(&self) -> LadduPhysicsResult<i32> {
        self.charm
            .ok_or(LadduPhysicsError::MissingParticleProperty { property: "charm" })
            .clone()
    }
    /// Get the particle's bottomness
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when bottomness
    /// is unknown.
    pub fn bottomness(&self) -> LadduPhysicsResult<i32> {
        self.bottomness
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "bottomness",
            })
            .clone()
    }
    /// Get the particle's topness
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when topness is
    /// unknown.
    pub fn topness(&self) -> LadduPhysicsResult<i32> {
        self.topness
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "topness",
            })
            .clone()
    }
    /// Get the particle's baryon number
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the baryon
    /// number is unknown.
    pub fn baryon_number(&self) -> LadduPhysicsResult<i32> {
        self.baryon_number
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "baryon_number",
            })
            .clone()
    }
    /// Get the particle's electron lepton number
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the electron
    /// lepton number is unknown.
    pub fn electron_lepton_number(&self) -> LadduPhysicsResult<i32> {
        self.electron_lepton_number
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "electron_lepton_number",
            })
            .clone()
    }
    /// Get the particle's muon lepton number
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the muon
    /// lepton number is unknown.
    pub fn muon_lepton_number(&self) -> LadduPhysicsResult<i32> {
        self.muon_lepton_number
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "muon_lepton_number",
            })
            .clone()
    }
    /// Get the particle's tau lepton number
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the tau
    /// lepton number is unknown.
    pub fn tau_lepton_number(&self) -> LadduPhysicsResult<i32> {
        self.tau_lepton_number
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "tau_lepton_number",
            })
            .clone()
    }
    /// Get the particle's statistics
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the
    /// statistics are unknown.
    pub fn statistics(&self) -> LadduPhysicsResult<Statistics> {
        self.statistics
            .ok_or(LadduPhysicsError::MissingParticleProperty {
                property: "statistics",
            })
            .clone()
    }
    /// Get the particle's mass.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError::MissingParticleProperty`] when the mass is
    /// unknown.
    pub fn mass(&self) -> LadduPhysicsResult<f64> {
        self.mass
            .ok_or(LadduPhysicsError::MissingParticleProperty { property: "mass" })
    }

    /// Construct a particle with no specified properties.
    pub fn unknown() -> Self {
        Self::default()
    }

    /// Construct a particle with the given spin and parity.
    /// Construct a particle with the given spin and intrinsic parity.
    pub fn jp(j: J, p: Parity) -> Self {
        Self {
            spin: Some(j),
            parity: Some(p),
            statistics: Some(Statistics::from_spin(j)),
            ..Self::default()
        }
    }
    /// Construct a particle with the given spin, parity, and C-parity.
    pub fn jpc(j: J, p: Parity, c: Parity) -> Self {
        Self {
            spin: Some(j),
            parity: Some(p),
            c_parity: Some(c),
            statistics: Some(Statistics::from_spin(j)),
            ..Self::default()
        }
    }

    /// A Boson-like state with spin `j` and zero baryon or lepton number
    pub fn boson(j: L) -> Self {
        let mut particle = Self::unknown().with_spin(j.into());
        particle.baryon_number = Some(0);
        particle.electron_lepton_number = Some(0);
        particle.muon_lepton_number = Some(0);
        particle.tau_lepton_number = Some(0);
        particle
    }

    /// Construct a lepton-like state with the supplied family lepton numbers.
    pub fn lepton(e: i32, m: i32, t: i32) -> Self {
        let mut particle = Self::unknown().with_zero_flavor();
        particle.baryon_number = Some(0);
        particle.electron_lepton_number = Some(e);
        particle.muon_lepton_number = Some(m);
        particle.tau_lepton_number = Some(t);
        particle
    }

    /// A hadron-like state with zero lepton number.
    /// Does not assume baryon number, charge, or flavor.
    pub fn hadron() -> Self {
        Self::unknown().with_zero_lepton_numbers()
    }

    /// A meson-like hadron with zero baryon and lepton number.
    /// Does not assume charge or flavor.
    pub fn meson() -> Self {
        let mut particle = Self::hadron();
        particle.baryon_number = Some(0);
        particle
    }

    /// A baryon-like hadron with baryon number `b` and zero lepton number.
    /// Usually `b = 1`; nuclei/dibaryons can use `b > 1`; antibaryons use negative values.
    pub fn baryon(b: i32) -> Self {
        let mut particle = Self::hadron();
        particle.baryon_number = Some(b);
        particle
    }

    /// Set the particle's name.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
    /// Set the particle's species.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when the species conflicts with existing
    /// self-conjugacy or antiparticle metadata.
    pub fn with_species(mut self, species: impl Into<String>) -> LadduPhysicsResult<Self> {
        let species = species.into();

        if self.self_conjugate == Some(true) {
            match &self.antiparticle_species {
                Some(anti) if anti != &species => {
                    return Err(LadduPhysicsError::invalid_relation(
                        "self-conjugate particle cannot have distinct species and antiparticle_species",
                    ));
                }
                None => self.antiparticle_species = Some(species.clone()),
                _ => {}
            }
        }

        self.species = Some(species);
        self.check_invariants()?;
        Ok(self)
    }
    /// Set the particle's antiparticle species.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when the antiparticle species conflicts
    /// with existing self-conjugacy or species metadata.
    pub fn with_antiparticle_species(
        mut self,
        antiparticle_species: impl Into<String>,
    ) -> LadduPhysicsResult<Self> {
        let antiparticle_species = antiparticle_species.into();

        if self.self_conjugate == Some(true) {
            match &self.species {
                Some(species) if species != &antiparticle_species => {
                    return Err(LadduPhysicsError::invalid_relation(
                        "self-conjugate particle cannot have distinct species and antiparticle_species",
                    ));
                }
                None => self.species = Some(antiparticle_species.clone()),
                _ => {}
            }
        }

        self.antiparticle_species = Some(antiparticle_species);
        self.check_invariants()?;
        Ok(self)
    }

    /// Set both particle and antiparticle species names.
    ///
    /// Equal names mark the particle as self-conjugate.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when the resulting species and quantum
    /// number metadata violate particle invariants.
    pub fn with_species_names(
        mut self,
        species: impl Into<String>,
        antiparticle_species: impl Into<String>,
    ) -> LadduPhysicsResult<Self> {
        let species = species.into();
        let antiparticle_species = antiparticle_species.into();

        self.species = Some(species.clone());
        self.antiparticle_species = Some(antiparticle_species.clone());
        self.self_conjugate = Some(species == antiparticle_species);

        self.fill_zero_additive_qns_if_self_conjugate();
        self.check_invariants()?;

        Ok(self)
    }

    /// Set whether the particle is its own antiparticle.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when `value` conflicts with species names,
    /// C-parity, or nonzero additive quantum numbers.
    pub fn with_self_conjugate(mut self, value: bool) -> LadduPhysicsResult<Self> {
        if value {
            if let (Some(species), Some(anti)) = (&self.species, &self.antiparticle_species)
                && species != anti
            {
                return Err(LadduPhysicsError::invalid_relation(
                    "self-conjugate particle cannot have distinct species and antiparticle_species",
                ));
            }
            match (&self.species, &self.antiparticle_species) {
                (Some(species), None) => self.antiparticle_species = Some(species.clone()),
                (None, Some(anti)) => self.species = Some(anti.clone()),
                _ => {}
            }
            self.fill_zero_additive_qns_if_self_conjugate();
        } else {
            if self.c_parity.is_some() {
                return Err(LadduPhysicsError::invalid_relation(
                    "non-self-conjugate particles cannot have C-parity",
                ));
            }
        }
        self.self_conjugate = Some(value);

        self.check_invariants()?;
        Ok(self)
    }

    /// Set one species name and mark the particle as self-conjugate.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when existing particle metadata is
    /// inconsistent with self-conjugacy.
    pub fn with_self_conjugate_species(
        mut self,
        species: impl Into<String>,
    ) -> LadduPhysicsResult<Self> {
        let species = species.into();

        self.species = Some(species.clone());
        self.antiparticle_species = Some(species);
        self.self_conjugate = Some(true);

        self.fill_zero_additive_qns_if_self_conjugate();
        self.check_invariants()?;

        Ok(self)
    }

    /// Set the particle's spin.
    pub fn with_spin(mut self, j: J) -> Self {
        self.spin = Some(j);
        self.statistics = Some(Statistics::from_spin(j));
        self
    }
    /// Set the particle's intrinsic parity.
    pub fn with_parity(mut self, p: Parity) -> Self {
        self.parity = Some(p);
        self
    }
    /// Set the particle's intrinsic C-parity.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when C-parity conflicts with the
    /// particle's self-conjugacy or additive quantum numbers.
    pub fn with_c_parity(mut self, c: Parity) -> LadduPhysicsResult<Self> {
        if self.self_conjugate == Some(false) {
            return Err(LadduPhysicsError::invalid_relation(
                "C-parity is only applicable to self-conjugate particles",
            ));
        }

        self.c_parity = Some(c);

        if self.self_conjugate.is_none() {
            self = self.with_self_conjugate(true)?;
        }

        self.check_invariants()?;
        Ok(self)
    }
    /// Set the particle's intrinsic G-parity.
    pub fn with_g_parity(mut self, g: Parity) -> Self {
        self.g_parity = Some(g);
        self
    }
    /// Set the particle's electric charge.
    pub fn with_charge(mut self, q: i32) -> Self {
        self.charge = Some(q);
        self
    }
    /// Set the particle's isospin state.
    pub fn with_isospin(mut self, isospin: Isospin) -> Self {
        self.isospin = Some(isospin);
        self
    }
    /// Set the particle's total strangeness.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when nonzero strangeness conflicts with
    /// self-conjugacy.
    pub fn with_strangeness(self, s: i32) -> LadduPhysicsResult<Self> {
        self.with_additive_qn("strangeness", |p| &mut p.strangeness, s)
    }
    /// Set the particle's total charm.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when nonzero charm conflicts with
    /// self-conjugacy.
    pub fn with_charm(self, c: i32) -> LadduPhysicsResult<Self> {
        self.with_additive_qn("charm", |p| &mut p.charm, c)
    }
    /// Set the particle's total bottomness.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when nonzero bottomness conflicts with
    /// self-conjugacy.
    pub fn with_bottomness(self, b: i32) -> LadduPhysicsResult<Self> {
        self.with_additive_qn("bottomness", |p| &mut p.bottomness, b)
    }
    /// Set the particle's total topness.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when nonzero topness conflicts with
    /// self-conjugacy.
    pub fn with_topness(self, t: i32) -> LadduPhysicsResult<Self> {
        self.with_additive_qn("topness", |p| &mut p.topness, t)
    }
    /// Set strangeness, charm, bottomness, and topness together.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when a nonzero flavor quantum number
    /// conflicts with self-conjugacy.
    pub fn with_flavor(self, s: i32, c: i32, b: i32, t: i32) -> LadduPhysicsResult<Self> {
        self.with_strangeness(s)?
            .with_charm(c)?
            .with_bottomness(b)?
            .with_topness(t)
    }
    /// Set the particle's total baryon number.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when a nonzero baryon number conflicts
    /// with self-conjugacy.
    pub fn with_baryon_number(self, b: i32) -> LadduPhysicsResult<Self> {
        self.with_additive_qn("baryon_number", |p| &mut p.baryon_number, b)
    }
    /// Set the particle's electron lepton number.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when a nonzero electron lepton number
    /// conflicts with self-conjugacy.
    pub fn with_electron_lepton_number(self, e: i32) -> LadduPhysicsResult<Self> {
        self.with_additive_qn(
            "electron_lepton_number",
            |p| &mut p.electron_lepton_number,
            e,
        )
    }
    /// Set the particle's muon lepton number.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when a nonzero muon lepton number
    /// conflicts with self-conjugacy.
    pub fn with_muon_lepton_number(self, m: i32) -> LadduPhysicsResult<Self> {
        self.with_additive_qn("muon_lepton_number", |p| &mut p.muon_lepton_number, m)
    }
    /// Set the particle's tau lepton number.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when a nonzero tau lepton number
    /// conflicts with self-conjugacy.
    pub fn with_tau_lepton_number(self, t: i32) -> LadduPhysicsResult<Self> {
        self.with_additive_qn("tau_lepton_number", |p| &mut p.tau_lepton_number, t)
    }

    /// Set electron-, muon-, and tau-family lepton numbers together.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when a nonzero lepton number conflicts
    /// with self-conjugacy.
    pub fn with_lepton_numbers(self, e: i32, m: i32, t: i32) -> LadduPhysicsResult<Self> {
        self.with_electron_lepton_number(e)?
            .with_muon_lepton_number(m)?
            .with_tau_lepton_number(t)
    }

    /// Set the particle's statistical nature.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] if the spin and statistics do not match.
    pub fn with_statistics(mut self, s: Statistics) -> LadduPhysicsResult<Self> {
        if let Some(spin) = self.spin
            && Statistics::from_spin(spin) != s
        {
            return Err(LadduPhysicsError::invalid_relation(
                "spin and statistics must be consistent",
            ));
        }
        self.statistics = Some(s);
        Ok(self)
    }
    /// Set the particle's mass.
    pub fn with_mass(mut self, mass: f64) -> Self {
        self.mass = Some(mass);
        self
    }

    /// Set every flavor quantum number to zero.
    pub fn with_zero_flavor(mut self) -> Self {
        self.strangeness = Some(0);
        self.charm = Some(0);
        self.bottomness = Some(0);
        self.topness = Some(0);
        self
    }

    /// Set every family lepton number to zero.
    pub fn with_zero_lepton_numbers(mut self) -> Self {
        self.electron_lepton_number = Some(0);
        self.muon_lepton_number = Some(0);
        self.tau_lepton_number = Some(0);
        self
    }

    /// Set charge, flavor, baryon number, and all lepton numbers to zero.
    ///
    /// # Errors
    ///
    /// Returns [`LadduPhysicsError`] when the resulting metadata violates
    /// another particle invariant.
    pub fn with_zero_additive_quantum_numbers(mut self) -> LadduPhysicsResult<Self> {
        self.charge = Some(0);
        self.strangeness = Some(0);
        self.charm = Some(0);
        self.bottomness = Some(0);
        self.topness = Some(0);
        self.baryon_number = Some(0);
        self.electron_lepton_number = Some(0);
        self.muon_lepton_number = Some(0);
        self.tau_lepton_number = Some(0);

        self.check_invariants()?;
        Ok(self)
    }

    /// Returns true if `self` is the antiparticle of `other`.
    pub fn is_antiparticle_of(&self, other: &ParticleProperties) -> bool {
        let a_species = self.species.as_ref();
        let b_species = other.species.as_ref();

        let a_anti = self.antiparticle_species.as_ref();
        let b_anti = other.antiparticle_species.as_ref();

        match (a_species, b_species, a_anti, b_anti) {
            (Some(a), Some(b), Some(a_bar), Some(b_bar)) => a_bar == b && b_bar == a,
            (Some(_), Some(b), Some(a_bar), None) => a_bar == b,
            (Some(a), Some(_), None, Some(b_bar)) => b_bar == a,
            _ => false,
        }
    }

    /// External identifiers for the particle
    pub fn ids(&self) -> &IndexMap<String, ExternalId> {
        &self.ids
    }

    /// Return the first external identifier in the requested namespace.
    pub fn id(&self, namespace: &str) -> Option<&ExternalId> {
        self.ids.get(namespace)
    }

    /// Append an external identifier.
    pub fn with_id<Id: Into<ExternalId>>(mut self, namespace: &str, id: Id) -> Self {
        self.ids.insert(namespace.to_string(), id.into());
        self
    }

    /// Replace external identifiers.
    pub fn with_ids<I, S, Id>(mut self, ids: I) -> Self
    where
        I: IntoIterator<Item = (S, Id)>,
        S: AsRef<str>,
        Id: Into<ExternalId>,
    {
        self.ids = ids
            .into_iter()
            .map(|(s, id)| (s.as_ref().to_string(), id.into()))
            .collect();
        self
    }
}

impl ParticleProperties {
    fn additive_quantum_number_fields(&self) -> [(&'static str, Option<i32>); 9] {
        [
            ("charge", self.charge),
            ("strangeness", self.strangeness),
            ("charm", self.charm),
            ("bottomness", self.bottomness),
            ("topness", self.topness),
            ("baryon_number", self.baryon_number),
            ("electron_lepton_number", self.electron_lepton_number),
            ("muon_lepton_number", self.muon_lepton_number),
            ("tau_lepton_number", self.tau_lepton_number),
        ]
    }

    fn fill_zero_additive_qns_if_self_conjugate(&mut self) {
        if self.self_conjugate == Some(true) {
            self.charge.get_or_insert(0);
            self.strangeness.get_or_insert(0);
            self.charm.get_or_insert(0);
            self.bottomness.get_or_insert(0);
            self.topness.get_or_insert(0);
            self.baryon_number.get_or_insert(0);
            self.electron_lepton_number.get_or_insert(0);
            self.muon_lepton_number.get_or_insert(0);
            self.tau_lepton_number.get_or_insert(0);
        }
    }

    fn check_self_conjugate_additive_qns(&self) -> LadduPhysicsResult<()> {
        if self.self_conjugate == Some(true) {
            for (property, value) in self.additive_quantum_number_fields() {
                if matches!(value, Some(v) if v != 0) {
                    return Err(LadduPhysicsError::invalid_relation(format!(
                        "self-conjugate particles must have {property} = 0"
                    )));
                }
            }
        }
        Ok(())
    }

    fn check_c_parity_allowed(&self) -> LadduPhysicsResult<()> {
        if self.c_parity.is_some() && self.self_conjugate == Some(false) {
            return Err(LadduPhysicsError::invalid_relation(
                "C-parity is only applicable to self-conjugate particles",
            ));
        }
        Ok(())
    }

    fn check_invariants(&self) -> LadduPhysicsResult<()> {
        self.check_self_conjugate_additive_qns()?;
        self.check_c_parity_allowed()?;
        Ok(())
    }

    fn with_additive_qn(
        mut self,
        property: &'static str,
        field: fn(&mut Self) -> &mut Option<i32>,
        value: i32,
    ) -> LadduPhysicsResult<Self> {
        if self.self_conjugate == Some(true) && value != 0 {
            return Err(LadduPhysicsError::invalid_value(
                property,
                "0 for self-conjugate particles",
                value,
            ));
        }

        *field(&mut self) = Some(value);
        self.check_invariants()?;
        Ok(self)
    }
}

fn validate_projection(spin: J, projection: M) -> LadduPhysicsResult<()> {
    if projection.doubled().unsigned_abs() > spin.doubled() {
        return Err(LadduPhysicsError::invalid_relation(format!(
            "spin projection must satisfy -J <= m <= J, got J = {spin}, m = {projection}"
        )));
    }
    if !spin.has_same_parity_as(projection) {
        return Err(LadduPhysicsError::invalid_relation(format!(
            "spin projection must have the same integer/half-integer parity as spin, got J = {spin}, m = {projection}"
        )));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{ExternalId, ParticleProperties};

    #[test]
    fn particle_properties_store_external_ids() {
        let properties = ParticleProperties::unknown()
            .with_id("pdg", ExternalId::code(310))
            .with_id("gluex", ExternalId::label("ks-short"));

        assert_eq!(properties.ids().len(), 2);
        assert_eq!(
            properties.id("pdg").and_then(ExternalId::code_value),
            Some(310)
        );
        assert_eq!(
            properties.id("gluex").and_then(ExternalId::label_value),
            Some("ks-short")
        );
        assert_eq!(properties.id("missing"), None);

        let replaced = properties.with_ids([("geant", ExternalId::code(16))]);
        assert_eq!(replaced.ids().len(), 1);
        assert_eq!(
            replaced.id("geant").and_then(ExternalId::code_value),
            Some(16)
        );
    }
}