laddu-core 0.18.0

Core of the laddu library
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
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
use std::{array, collections::HashMap};

use nalgebra::{SMatrix, SVector};
use num::complex::Complex64;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;

use crate::{
    amplitudes::{AmplitudeID, Parameter, ParameterMap},
    LadduError, LadduResult,
};

fn is_glob_selector(selector: &str) -> bool {
    selector.contains('*') || selector.contains('?')
}

fn glob_matches(pattern: &str, text: &str) -> bool {
    let pattern = pattern.chars().collect::<Vec<_>>();
    let text = text.chars().collect::<Vec<_>>();
    let mut table = vec![vec![false; text.len() + 1]; pattern.len() + 1];
    table[0][0] = true;
    for pattern_idx in 1..=pattern.len() {
        if pattern[pattern_idx - 1] == '*' {
            table[pattern_idx][0] = table[pattern_idx - 1][0];
        }
    }
    for pattern_idx in 1..=pattern.len() {
        for text_idx in 1..=text.len() {
            table[pattern_idx][text_idx] = match pattern[pattern_idx - 1] {
                '*' => table[pattern_idx - 1][text_idx] || table[pattern_idx][text_idx - 1],
                '?' => table[pattern_idx - 1][text_idx - 1],
                character => {
                    character == text[text_idx - 1] && table[pattern_idx - 1][text_idx - 1]
                }
            };
        }
    }
    table[pattern.len()][text.len()]
}

/// This struct holds references to the constants and free parameters used in the fit so that they
/// may be obtained from their corresponding [`ParameterID`].
#[derive(Debug)]
pub struct Parameters {
    values: Vec<f64>,
    n_free: usize,
    storage_to_assembled: Vec<usize>,
}

impl Parameters {
    /// Create a full parameter store from assembled values and the number of free parameters.
    pub fn new(values: Vec<f64>, n_free: usize, storage_to_assembled: Vec<usize>) -> Self {
        Self {
            values,
            n_free,
            storage_to_assembled,
        }
    }
    /// Borrow the assembled parameter values.
    pub fn values(&self) -> &[f64] {
        &self.values
    }
    /// Create a new parameter store with the same layout and different assembled values.
    pub fn with_values(&self, values: Vec<f64>) -> Self {
        Self {
            values,
            n_free: self.n_free,
            storage_to_assembled: self.storage_to_assembled.clone(),
        }
    }
    /// Obtain a parameter value or constant value from the given [`ParameterID`].
    pub fn get(&self, pid: ParameterID) -> f64 {
        self.assembled_index(pid)
            .and_then(|index| self.values.get(index))
            .copied()
            .unwrap_or(f64::NAN)
    }
    /// Return the assembled index for the given registered parameter.
    pub fn assembled_index(&self, pid: ParameterID) -> Option<usize> {
        self.storage_index(pid)
            .and_then(|index| self.storage_to_assembled.get(index).copied())
    }
    /// Return the free-parameter index for the given registered parameter, if it is currently
    /// free.
    pub fn free_index(&self, pid: ParameterID) -> Option<usize> {
        let index = self.assembled_index(pid)?;
        (index < self.n_free).then_some(index)
    }
    fn storage_index(&self, pid: ParameterID) -> Option<usize> {
        match pid {
            ParameterID::Parameter(index) | ParameterID::Constant(index) => Some(index),
            ParameterID::Uninit => None,
        }
    }
    /// Return the number of free parameters.
    pub fn len(&self) -> usize {
        self.n_free
    }

    /// Return whether there are no free parameters.
    pub fn is_empty(&self) -> bool {
        self.n_free == 0
    }
}

/// The main resource manager for cached values, amplitudes, parameters, and constants.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Resources {
    amplitudes: HashMap<String, AmplitudeID>,
    /// A list indicating which amplitudes are active (using [`AmplitudeID`]s as indices)
    pub active: Vec<bool>,
    #[serde(default)]
    active_indices: Vec<usize>,
    /// The registered parameters and constants used by this resource set.
    pub parameter_map: ParameterMap,
    /// The [`Cache`] for each [`EventData`](`crate::data::EventData`)
    pub caches: Vec<Cache>,
    scalar_cache_names: HashMap<String, usize>,
    complex_scalar_cache_names: HashMap<String, usize>,
    vector_cache_names: HashMap<String, usize>,
    complex_vector_cache_names: HashMap<String, usize>,
    matrix_cache_names: HashMap<String, usize>,
    complex_matrix_cache_names: HashMap<String, usize>,
    cache_size: usize,
}

/// A single cache entry corresponding to precomputed data for a particular
/// [`EventData`](crate::data::EventData) in a [`Dataset`](crate::data::Dataset).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Cache(Vec<f64>);
impl Cache {
    fn new(cache_size: usize) -> Self {
        Self(vec![0.0; cache_size])
    }
    /// Store a scalar value with the corresponding [`ScalarID`].
    pub fn store_scalar(&mut self, sid: ScalarID, value: f64) {
        self.0[sid.0] = value;
    }
    /// Store a complex scalar value with the corresponding [`ComplexScalarID`].
    pub fn store_complex_scalar(&mut self, csid: ComplexScalarID, value: Complex64) {
        self.0[csid.0] = value.re;
        self.0[csid.1] = value.im;
    }
    /// Store a vector with the corresponding [`VectorID`].
    pub fn store_vector<const R: usize>(&mut self, vid: VectorID<R>, value: SVector<f64, R>) {
        vid.0
            .into_iter()
            .enumerate()
            .for_each(|(vi, i)| self.0[i] = value[vi]);
    }
    /// Store a complex-valued vector with the corresponding [`ComplexVectorID`].
    pub fn store_complex_vector<const R: usize>(
        &mut self,
        cvid: ComplexVectorID<R>,
        value: SVector<Complex64, R>,
    ) {
        cvid.0
            .into_iter()
            .enumerate()
            .for_each(|(vi, i)| self.0[i] = value[vi].re);
        cvid.1
            .into_iter()
            .enumerate()
            .for_each(|(vi, i)| self.0[i] = value[vi].im);
    }
    /// Store a matrix with the corresponding [`MatrixID`].
    pub fn store_matrix<const R: usize, const C: usize>(
        &mut self,
        mid: MatrixID<R, C>,
        value: SMatrix<f64, R, C>,
    ) {
        mid.0.into_iter().enumerate().for_each(|(vi, row)| {
            row.into_iter()
                .enumerate()
                .for_each(|(vj, k)| self.0[k] = value[(vi, vj)])
        });
    }
    /// Store a complex-valued matrix with the corresponding [`ComplexMatrixID`].
    pub fn store_complex_matrix<const R: usize, const C: usize>(
        &mut self,
        cmid: ComplexMatrixID<R, C>,
        value: SMatrix<Complex64, R, C>,
    ) {
        cmid.0.into_iter().enumerate().for_each(|(vi, row)| {
            row.into_iter()
                .enumerate()
                .for_each(|(vj, k)| self.0[k] = value[(vi, vj)].re)
        });
        cmid.1.into_iter().enumerate().for_each(|(vi, row)| {
            row.into_iter()
                .enumerate()
                .for_each(|(vj, k)| self.0[k] = value[(vi, vj)].im)
        });
    }
    /// Retrieve a scalar value from the [`Cache`].
    pub fn get_scalar(&self, sid: ScalarID) -> f64 {
        self.0[sid.0]
    }
    /// Retrieve a complex scalar value from the [`Cache`].
    pub fn get_complex_scalar(&self, csid: ComplexScalarID) -> Complex64 {
        Complex64::new(self.0[csid.0], self.0[csid.1])
    }
    /// Retrieve a vector from the [`Cache`].
    pub fn get_vector<const R: usize>(&self, vid: VectorID<R>) -> SVector<f64, R> {
        SVector::from_fn(|i, _| self.0[vid.0[i]])
    }
    /// Retrieve a complex-valued vector from the [`Cache`].
    pub fn get_complex_vector<const R: usize>(
        &self,
        cvid: ComplexVectorID<R>,
    ) -> SVector<Complex64, R> {
        SVector::from_fn(|i, _| Complex64::new(self.0[cvid.0[i]], self.0[cvid.1[i]]))
    }
    /// Retrieve a matrix from the [`Cache`].
    pub fn get_matrix<const R: usize, const C: usize>(
        &self,
        mid: MatrixID<R, C>,
    ) -> SMatrix<f64, R, C> {
        SMatrix::from_fn(|i, j| self.0[mid.0[i][j]])
    }
    /// Retrieve a complex-valued matrix from the [`Cache`].
    pub fn get_complex_matrix<const R: usize, const C: usize>(
        &self,
        cmid: ComplexMatrixID<R, C>,
    ) -> SMatrix<Complex64, R, C> {
        SMatrix::from_fn(|i, j| Complex64::new(self.0[cmid.0[i][j]], self.0[cmid.1[i][j]]))
    }
}

/// An object which acts as a tag to refer to either a free parameter or a constant value.
#[derive(Default, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum ParameterID {
    /// A free parameter.
    Parameter(usize),
    /// A constant value.
    Constant(usize),
    /// An uninitialized ID
    #[default]
    Uninit,
}

/// A tag for retrieving or storing a scalar value in a [`Cache`].
#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize)]
pub struct ScalarID(usize);

/// A tag for retrieving or storing a complex scalar value in a [`Cache`].
#[derive(Copy, Clone, Default, Debug, Serialize, Deserialize)]
pub struct ComplexScalarID(usize, usize);

/// A tag for retrieving or storing a vector in a [`Cache`].
#[serde_as]
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct VectorID<const R: usize>(#[serde_as(as = "[_; R]")] [usize; R]);

impl<const R: usize> Default for VectorID<R> {
    fn default() -> Self {
        Self([0; R])
    }
}

/// A tag for retrieving or storing a complex-valued vector in a [`Cache`].
#[serde_as]
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct ComplexVectorID<const R: usize>(
    #[serde_as(as = "[_; R]")] [usize; R],
    #[serde_as(as = "[_; R]")] [usize; R],
);

impl<const R: usize> Default for ComplexVectorID<R> {
    fn default() -> Self {
        Self([0; R], [0; R])
    }
}

/// A tag for retrieving or storing a matrix in a [`Cache`].
#[serde_as]
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct MatrixID<const R: usize, const C: usize>(
    #[serde_as(as = "[[_; C]; R]")] [[usize; C]; R],
);

impl<const R: usize, const C: usize> Default for MatrixID<R, C> {
    fn default() -> Self {
        Self([[0; C]; R])
    }
}

/// A tag for retrieving or storing a complex-valued matrix in a [`Cache`].
#[serde_as]
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct ComplexMatrixID<const R: usize, const C: usize>(
    #[serde_as(as = "[[_; C]; R]")] [[usize; C]; R],
    #[serde_as(as = "[[_; C]; R]")] [[usize; C]; R],
);

impl<const R: usize, const C: usize> Default for ComplexMatrixID<R, C> {
    fn default() -> Self {
        Self([[0; C]; R], [[0; C]; R])
    }
}

impl Resources {
    /// Rename a single registered parameter.
    pub fn rename_parameter(&mut self, old: &str, new: &str) -> LadduResult<()> {
        self.parameter_map.rename_parameter(old, new)
    }

    /// Rename multiple registered parameters.
    pub fn rename_parameters(&mut self, mapping: &HashMap<String, String>) -> LadduResult<()> {
        self.parameter_map.rename_parameters(mapping)
    }

    /// Mark a registered parameter as free.
    pub fn free_parameter(&self, name: &str) -> LadduResult<()> {
        self.parameter_map.free_parameter(name)
    }

    /// Fix a registered parameter to the supplied value.
    pub fn fix_parameter(&self, name: &str, value: f64) -> LadduResult<()> {
        self.parameter_map.fix_parameter(name, value)
    }

    /// The list of free parameter names.
    pub fn free_parameter_names(&self) -> Vec<String> {
        self.parameter_map.free().names()
    }

    /// The list of fixed parameter names.
    pub fn fixed_parameter_names(&self) -> Vec<String> {
        self.parameter_map.fixed().names()
    }

    /// All parameter names (free first, then fixed).
    pub fn parameter_names(&self) -> Vec<String> {
        self.free_parameter_names()
            .into_iter()
            .chain(self.fixed_parameter_names())
            .collect()
    }

    /// Number of free parameters.
    pub fn n_free_parameters(&self) -> usize {
        self.parameter_map.free().len()
    }

    /// Number of fixed parameters.
    pub fn n_fixed_parameters(&self) -> usize {
        self.parameter_map.fixed().len()
    }

    /// Total number of parameters.
    pub fn n_parameters(&self) -> usize {
        self.n_free_parameters() + self.n_fixed_parameters()
    }

    fn rebuild_active_indices(&mut self) {
        self.active_indices.clear();
        self.active_indices.extend(
            self.active
                .iter()
                .enumerate()
                .filter_map(|(idx, &is_active)| if is_active { Some(idx) } else { None }),
        );
    }

    pub(crate) fn refresh_active_indices(&mut self) {
        self.rebuild_active_indices();
    }

    /// Return the indices of active amplitudes.
    pub fn active_indices(&self) -> &[usize] {
        &self.active_indices
    }

    fn selector_indices(&self, selector: &str) -> Vec<usize> {
        if is_glob_selector(selector) {
            self.amplitudes
                .iter()
                .filter_map(|(name, amplitude)| {
                    if glob_matches(selector, name) {
                        Some(amplitude.1)
                    } else {
                        None
                    }
                })
                .collect()
        } else {
            self.amplitudes
                .get(selector)
                .map(|amplitude| vec![amplitude.1])
                .unwrap_or_default()
        }
    }

    fn set_activation_state_by_selector(
        &mut self,
        selector: &str,
        active: bool,
        strict: bool,
    ) -> LadduResult<bool> {
        let indices = self.selector_indices(selector);
        if indices.is_empty() {
            if strict {
                return Err(LadduError::AmplitudeNotFoundError {
                    name: selector.to_string(),
                });
            }
            return Ok(false);
        }
        let mut changed = false;
        for idx in indices {
            if self.active[idx] != active {
                self.active[idx] = active;
                changed = true;
            }
        }
        Ok(changed)
    }

    fn selector_indices_many<T: AsRef<str>>(
        &self,
        selectors: &[T],
        strict: bool,
    ) -> LadduResult<Vec<usize>> {
        let mut indices = Vec::new();
        for selector in selectors {
            let selector_ref = selector.as_ref();
            let selector_indices = self.selector_indices(selector_ref);
            if selector_indices.is_empty() && strict {
                return Err(LadduError::AmplitudeNotFoundError {
                    name: selector_ref.to_string(),
                });
            }
            indices.extend(selector_indices);
        }
        indices.sort_unstable();
        indices.dedup();
        Ok(indices)
    }

    fn isolate_indices(&mut self, indices: &[usize]) {
        let mut changed = false;
        for (idx, active) in self.active.iter_mut().enumerate() {
            let next_active = indices.binary_search(&idx).is_ok();
            if *active != next_active {
                *active = next_active;
                changed = true;
            }
        }
        if changed {
            self.rebuild_active_indices();
        }
    }

    /// Activate an [`Amplitude`](crate::amplitudes::Amplitude) by name.
    pub fn activate<T: AsRef<str>>(&mut self, name: T) {
        if self
            .set_activation_state_by_selector(name.as_ref(), true, false)
            .unwrap_or(false)
        {
            self.rebuild_active_indices();
        }
    }
    /// Activate several [`Amplitude`](crate::amplitudes::Amplitude)s by name.
    pub fn activate_many<T: AsRef<str>>(&mut self, names: &[T]) {
        let mut changed = false;
        for name in names {
            if self
                .set_activation_state_by_selector(name.as_ref(), true, false)
                .unwrap_or(false)
            {
                changed = true;
            }
        }
        if changed {
            self.rebuild_active_indices();
        }
    }
    /// Activate an [`Amplitude`](crate::amplitudes::Amplitude) by name, returning an error if it is missing.
    pub fn activate_strict<T: AsRef<str>>(&mut self, name: T) -> LadduResult<()> {
        if self.set_activation_state_by_selector(name.as_ref(), true, true)? {
            self.rebuild_active_indices();
        }
        Ok(())
    }
    /// Activate several [`Amplitude`](crate::amplitudes::Amplitude)s by name, returning an error if any are missing.
    pub fn activate_many_strict<T: AsRef<str>>(&mut self, names: &[T]) -> LadduResult<()> {
        let mut changed = false;
        for name in names {
            if self.set_activation_state_by_selector(name.as_ref(), true, true)? {
                changed = true;
            }
        }
        if changed {
            self.rebuild_active_indices();
        }
        Ok(())
    }
    /// Activate all registered [`Amplitude`](crate::amplitudes::Amplitude)s.
    pub fn activate_all(&mut self) {
        let mut changed = false;
        for active in self.active.iter_mut() {
            if !*active {
                *active = true;
                changed = true;
            }
        }
        if changed {
            self.rebuild_active_indices();
        }
    }
    /// Deactivate an [`Amplitude`](crate::amplitudes::Amplitude) by name.
    pub fn deactivate<T: AsRef<str>>(&mut self, name: T) {
        if self
            .set_activation_state_by_selector(name.as_ref(), false, false)
            .unwrap_or(false)
        {
            self.rebuild_active_indices();
        }
    }
    /// Deactivate several [`Amplitude`](crate::amplitudes::Amplitude)s by name.
    pub fn deactivate_many<T: AsRef<str>>(&mut self, names: &[T]) {
        let mut changed = false;
        for name in names {
            if self
                .set_activation_state_by_selector(name.as_ref(), false, false)
                .unwrap_or(false)
            {
                changed = true;
            }
        }
        if changed {
            self.rebuild_active_indices();
        }
    }
    /// Deactivate an [`Amplitude`](crate::amplitudes::Amplitude) by name, returning an error if it is missing.
    pub fn deactivate_strict<T: AsRef<str>>(&mut self, name: T) -> LadduResult<()> {
        if self.set_activation_state_by_selector(name.as_ref(), false, true)? {
            self.rebuild_active_indices();
        }
        Ok(())
    }
    /// Deactivate several [`Amplitude`](crate::amplitudes::Amplitude)s by name, returning an error if any are missing.
    pub fn deactivate_many_strict<T: AsRef<str>>(&mut self, names: &[T]) -> LadduResult<()> {
        let mut changed = false;
        for name in names {
            if self.set_activation_state_by_selector(name.as_ref(), false, true)? {
                changed = true;
            }
        }
        if changed {
            self.rebuild_active_indices();
        }
        Ok(())
    }
    /// Deactivate all registered [`Amplitude`](crate::amplitudes::Amplitude)s.
    pub fn deactivate_all(&mut self) {
        let mut changed = false;
        for active in self.active.iter_mut() {
            if *active {
                *active = false;
                changed = true;
            }
        }
        if changed {
            self.rebuild_active_indices();
        }
    }
    /// Isolate an [`Amplitude`](crate::amplitudes::Amplitude) by name (deactivate the rest).
    pub fn isolate<T: AsRef<str>>(&mut self, name: T) {
        let indices = self.selector_indices(name.as_ref());
        if !indices.is_empty() || !is_glob_selector(name.as_ref()) {
            self.isolate_indices(&indices);
        }
    }
    /// Isolate an [`Amplitude`](crate::amplitudes::Amplitude) by name (deactivate the rest), returning an error if it is missing.
    pub fn isolate_strict<T: AsRef<str>>(&mut self, name: T) -> LadduResult<()> {
        let indices = self.selector_indices_many(&[name], true)?;
        self.isolate_indices(&indices);
        Ok(())
    }
    /// Isolate several [`Amplitude`](crate::amplitudes::Amplitude)s by name (deactivate the rest).
    pub fn isolate_many<T: AsRef<str>>(&mut self, names: &[T]) {
        if let Ok(indices) = self.selector_indices_many(names, false) {
            if !indices.is_empty() || names.iter().any(|name| !is_glob_selector(name.as_ref())) {
                self.isolate_indices(&indices);
            }
        }
    }
    /// Isolate several [`Amplitude`](crate::amplitudes::Amplitude)s by name (deactivate the rest), returning an error if any are missing.
    pub fn isolate_many_strict<T: AsRef<str>>(&mut self, names: &[T]) -> LadduResult<()> {
        let indices = self.selector_indices_many(names, true)?;
        self.isolate_indices(&indices);
        Ok(())
    }
    /// Register an [`Amplitude`](crate::amplitudes::Amplitude) with the [`Resources`] manager.
    /// This method should be called at the end of the
    /// [`Amplitude::register`](crate::amplitudes::Amplitude::register) method. The
    /// [`Amplitude`](crate::amplitudes::Amplitude) should probably obtain a name [`String`] in its
    /// constructor.
    ///
    /// # Errors
    ///
    /// The [`Amplitude`](crate::amplitudes::Amplitude)'s name must be unique and not already
    /// registered, else this will return a [`RegistrationError`][LadduError::RegistrationError].
    pub fn register_amplitude(&mut self, name: &str) -> LadduResult<AmplitudeID> {
        if self.amplitudes.contains_key(name) {
            return Err(LadduError::RegistrationError {
                name: name.to_string(),
            });
        }
        let next_id = AmplitudeID(name.to_string(), self.amplitudes.len());
        self.amplitudes.insert(name.to_string(), next_id.clone());
        self.active.push(true);
        self.rebuild_active_indices();
        Ok(next_id)
    }

    /// Fetch the [`AmplitudeID`] for a previously registered amplitude by name.
    pub fn amplitude_id(&self, name: &str) -> Option<AmplitudeID> {
        self.amplitudes.get(name).cloned()
    }

    /// register a parameter. this method should be called within
    /// [`amplitude::register`](crate::amplitudes::amplitude::register). the resulting
    /// [`ParameterID`] should be stored to retrieve the value from the [`Parameters`] wrapper.
    ///
    /// # Errors
    ///
    /// Returns an error if the parameter is unnamed, if the name is reused with incompatible
    /// fixed/free status or fixed value, or if renaming causes a conflict.
    pub fn register_parameter(&mut self, p: &Parameter) -> LadduResult<ParameterID> {
        self.parameter_map.register_parameter(p)
    }
    pub(crate) fn reserve_cache(&mut self, num_events: usize) {
        self.caches = vec![Cache::new(self.cache_size); num_events]
    }
    /// Register a scalar with an optional name (names are unique to the [`Cache`] so two different
    /// registrations of the same type which share a name will also share values and may overwrite
    /// each other). This method should be called within the
    /// [`Amplitude::register`](crate::amplitudes::Amplitude::register) method, and the
    /// resulting [`ScalarID`] should be stored to use later to retrieve the value from the [`Cache`].
    pub fn register_scalar(&mut self, name: Option<&str>) -> ScalarID {
        let first_index = if let Some(name) = name {
            *self
                .scalar_cache_names
                .entry(name.to_string())
                .or_insert_with(|| {
                    self.cache_size += 1;
                    self.cache_size - 1
                })
        } else {
            self.cache_size += 1;
            self.cache_size - 1
        };
        ScalarID(first_index)
    }
    /// Register a complex scalar with an optional name (names are unique to the [`Cache`] so two different
    /// registrations of the same type which share a name will also share values and may overwrite
    /// each other). This method should be called within the
    /// [`Amplitude::register`](crate::amplitudes::Amplitude::register) method, and the
    /// resulting [`ComplexScalarID`] should be stored to use later to retrieve the value from the [`Cache`].
    pub fn register_complex_scalar(&mut self, name: Option<&str>) -> ComplexScalarID {
        let first_index = if let Some(name) = name {
            *self
                .complex_scalar_cache_names
                .entry(name.to_string())
                .or_insert_with(|| {
                    self.cache_size += 2;
                    self.cache_size - 2
                })
        } else {
            self.cache_size += 2;
            self.cache_size - 2
        };
        ComplexScalarID(first_index, first_index + 1)
    }
    /// Register a vector with an optional name (names are unique to the [`Cache`] so two different
    /// registrations of the same type which share a name will also share values and may overwrite
    /// each other). This method should be called within the
    /// [`Amplitude::register`](crate::amplitudes::Amplitude::register) method, and the
    /// resulting [`VectorID`] should be stored to use later to retrieve the value from the [`Cache`].
    pub fn register_vector<const R: usize>(&mut self, name: Option<&str>) -> VectorID<R> {
        let first_index = if let Some(name) = name {
            *self
                .vector_cache_names
                .entry(name.to_string())
                .or_insert_with(|| {
                    self.cache_size += R;
                    self.cache_size - R
                })
        } else {
            self.cache_size += R;
            self.cache_size - R
        };
        VectorID(array::from_fn(|i| first_index + i))
    }
    /// Register a complex-valued vector with an optional name (names are unique to the [`Cache`] so two different
    /// registrations of the same type which share a name will also share values and may overwrite
    /// each other). This method should be called within the
    /// [`Amplitude::register`](crate::amplitudes::Amplitude::register) method, and the
    /// resulting [`ComplexVectorID`] should be stored to use later to retrieve the value from the [`Cache`].
    pub fn register_complex_vector<const R: usize>(
        &mut self,
        name: Option<&str>,
    ) -> ComplexVectorID<R> {
        let first_index = if let Some(name) = name {
            *self
                .complex_vector_cache_names
                .entry(name.to_string())
                .or_insert_with(|| {
                    self.cache_size += R * 2;
                    self.cache_size - (R * 2)
                })
        } else {
            self.cache_size += R * 2;
            self.cache_size - (R * 2)
        };
        ComplexVectorID(
            array::from_fn(|i| first_index + i),
            array::from_fn(|i| (first_index + R) + i),
        )
    }
    /// Register a matrix with an optional name (names are unique to the [`Cache`] so two different
    /// registrations of the same type which share a name will also share values and may overwrite
    /// each other). This method should be called within the
    /// [`Amplitude::register`](crate::amplitudes::Amplitude::register) method, and the
    /// resulting [`MatrixID`] should be stored to use later to retrieve the value from the [`Cache`].
    pub fn register_matrix<const R: usize, const C: usize>(
        &mut self,
        name: Option<&str>,
    ) -> MatrixID<R, C> {
        let first_index = if let Some(name) = name {
            *self
                .matrix_cache_names
                .entry(name.to_string())
                .or_insert_with(|| {
                    self.cache_size += R * C;
                    self.cache_size - (R * C)
                })
        } else {
            self.cache_size += R * C;
            self.cache_size - (R * C)
        };
        MatrixID(array::from_fn(|i| {
            array::from_fn(|j| first_index + i * C + j)
        }))
    }
    /// Register a complex-valued matrix with an optional name (names are unique to the [`Cache`] so two different
    /// registrations of the same type which share a name will also share values and may overwrite
    /// each other). This method should be called within the
    /// [`Amplitude::register`](crate::amplitudes::Amplitude::register) method, and the
    /// resulting [`ComplexMatrixID`] should be stored to use later to retrieve the value from the [`Cache`].
    pub fn register_complex_matrix<const R: usize, const C: usize>(
        &mut self,
        name: Option<&str>,
    ) -> ComplexMatrixID<R, C> {
        let first_index = if let Some(name) = name {
            *self
                .complex_matrix_cache_names
                .entry(name.to_string())
                .or_insert_with(|| {
                    self.cache_size += 2 * R * C;
                    self.cache_size - (2 * R * C)
                })
        } else {
            self.cache_size += 2 * R * C;
            self.cache_size - (2 * R * C)
        };
        ComplexMatrixID(
            array::from_fn(|i| array::from_fn(|j| first_index + i * C + j)),
            array::from_fn(|i| array::from_fn(|j| (first_index + R * C) + i * C + j)),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use nalgebra::{Matrix2, Vector2};
    use num::complex::Complex64;

    #[test]
    fn test_parameters() {
        let parameters = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let params = Parameters::new(parameters, 3, vec![0, 1, 2, 3, 4, 5]);

        assert_eq!(params.get(ParameterID::Parameter(0)), 1.0);
        assert_eq!(params.get(ParameterID::Parameter(1)), 2.0);
        assert_eq!(params.get(ParameterID::Parameter(2)), 3.0);
        assert_eq!(params.get(ParameterID::Constant(3)), 4.0);
        assert_eq!(params.get(ParameterID::Constant(4)), 5.0);
        assert_eq!(params.get(ParameterID::Constant(5)), 6.0);
        assert_eq!(params.free_index(ParameterID::Parameter(0)), Some(0));
        assert_eq!(params.free_index(ParameterID::Constant(3)), None);
        assert_eq!(params.len(), 3);
    }

    #[test]
    fn test_uninit_parameter_returns_nan() {
        let parameters = vec![1.0, 1.0];
        let params = Parameters::new(parameters, 1, vec![0, 1]);
        assert!(params.get(ParameterID::Uninit).is_nan());
        assert!(params.get(ParameterID::Parameter(3)).is_nan());
        assert!(params.get(ParameterID::Constant(3)).is_nan());
    }

    #[test]
    fn test_resources_amplitude_management() {
        let mut resources = Resources::default();

        let amp1 = resources.register_amplitude("amp1").unwrap();
        let amp2 = resources.register_amplitude("amp2").unwrap();

        assert!(resources.active[amp1.1]);
        assert!(resources.active[amp2.1]);

        resources.deactivate_strict("amp1").unwrap();
        assert!(!resources.active[amp1.1]);
        assert!(resources.active[amp2.1]);

        resources.activate_strict("amp1").unwrap();
        assert!(resources.active[amp1.1]);

        resources.deactivate_all();
        assert!(!resources.active[amp1.1]);
        assert!(!resources.active[amp2.1]);

        resources.activate_all();
        assert!(resources.active[amp1.1]);
        assert!(resources.active[amp2.1]);

        resources.isolate_strict("amp1").unwrap();
        assert!(resources.active[amp1.1]);
        assert!(!resources.active[amp2.1]);
    }

    #[test]
    fn test_resources_amplitude_glob_management() {
        let mut resources = Resources::default();

        let signal_s = resources.register_amplitude("signal.s").unwrap();
        let signal_d = resources.register_amplitude("signal.d").unwrap();
        let background = resources.register_amplitude("background").unwrap();

        resources.deactivate_strict("signal.*").unwrap();
        assert!(!resources.active[signal_s.1]);
        assert!(!resources.active[signal_d.1]);
        assert!(resources.active[background.1]);

        resources.activate_strict("signal.?").unwrap();
        assert!(resources.active[signal_s.1]);
        assert!(resources.active[signal_d.1]);
        assert!(resources.active[background.1]);

        resources.isolate_strict("signal.*").unwrap();
        assert!(resources.active[signal_s.1]);
        assert!(resources.active[signal_d.1]);
        assert!(!resources.active[background.1]);

        resources.activate_all();
        resources
            .isolate_many_strict(&["signal.s", "back*"])
            .unwrap();
        assert!(resources.active[signal_s.1]);
        assert!(!resources.active[signal_d.1]);
        assert!(resources.active[background.1]);

        assert!(resources.activate_strict("missing*").is_err());
        assert!(resources.deactivate_strict("missing?").is_err());
        assert!(resources.isolate_strict("missing*").is_err());
    }

    #[test]
    fn test_resources_non_strict_zero_match_glob_is_noop() {
        let mut resources = Resources::default();

        let signal = resources.register_amplitude("signal").unwrap();
        let background = resources.register_amplitude("background").unwrap();

        resources.deactivate("missing*");
        assert!(resources.active[signal.1]);
        assert!(resources.active[background.1]);

        resources.isolate("missing*");
        assert!(resources.active[signal.1]);
        assert!(resources.active[background.1]);
    }

    #[test]
    fn test_resources_parameter_registration() {
        let mut resources = Resources::default();

        let param1 = resources
            .register_parameter(&Parameter::new("param1"))
            .unwrap();
        let const1 = resources
            .register_parameter(&Parameter::new_fixed("const1", 1.0))
            .unwrap();

        match param1 {
            ParameterID::Parameter(idx) => assert_eq!(idx, 0),
            _ => panic!("Expected Parameter variant"),
        }

        match const1 {
            ParameterID::Constant(idx) => assert_eq!(idx, 1),
            _ => panic!("Expected Constant variant"),
        }
    }

    #[test]
    fn test_cache_scalar_operations() {
        let mut resources = Resources::default();

        let scalar1 = resources.register_scalar(Some("test_scalar"));
        let scalar2 = resources.register_scalar(None);
        let scalar3 = resources.register_scalar(Some("test_scalar"));

        resources.reserve_cache(1);
        let cache = &mut resources.caches[0];

        cache.store_scalar(scalar1, 1.0);
        cache.store_scalar(scalar2, 2.0);

        assert_eq!(cache.get_scalar(scalar1), 1.0);
        assert_eq!(cache.get_scalar(scalar2), 2.0);
        assert_eq!(cache.get_scalar(scalar3), 1.0);
    }

    #[test]
    fn test_cache_complex_operations() {
        let mut resources = Resources::default();

        let complex1 = resources.register_complex_scalar(Some("test_complex"));
        let complex2 = resources.register_complex_scalar(None);
        let complex3 = resources.register_complex_scalar(Some("test_complex"));

        resources.reserve_cache(1);
        let cache = &mut resources.caches[0];

        let value1 = Complex64::new(1.0, 2.0);
        let value2 = Complex64::new(3.0, 4.0);
        cache.store_complex_scalar(complex1, value1);
        cache.store_complex_scalar(complex2, value2);

        assert_eq!(cache.get_complex_scalar(complex1), value1);
        assert_eq!(cache.get_complex_scalar(complex2), value2);
        assert_eq!(cache.get_complex_scalar(complex3), value1);
    }

    #[test]
    fn test_cache_vector_operations() {
        let mut resources = Resources::default();

        let vector_id1: VectorID<2> = resources.register_vector(Some("test_vector"));
        let vector_id2: VectorID<2> = resources.register_vector(None);
        let vector_id3: VectorID<2> = resources.register_vector(Some("test_vector"));

        resources.reserve_cache(1);
        let cache = &mut resources.caches[0];

        let value1 = Vector2::new(1.0, 2.0);
        let value2 = Vector2::new(3.0, 4.0);
        cache.store_vector(vector_id1, value1);
        cache.store_vector(vector_id2, value2);

        assert_eq!(cache.get_vector(vector_id1), value1);
        assert_eq!(cache.get_vector(vector_id2), value2);
        assert_eq!(cache.get_vector(vector_id3), value1);
    }

    #[test]
    fn test_cache_complex_vector_operations() {
        let mut resources = Resources::default();

        let complex_vector_id1: ComplexVectorID<2> =
            resources.register_complex_vector(Some("test_complex_vector"));
        let complex_vector_id2: ComplexVectorID<2> = resources.register_complex_vector(None);
        let complex_vector_id3: ComplexVectorID<2> =
            resources.register_complex_vector(Some("test_complex_vector"));

        resources.reserve_cache(1);
        let cache = &mut resources.caches[0];

        let value1 = Vector2::new(Complex64::new(1.0, 2.0), Complex64::new(3.0, 4.0));
        let value2 = Vector2::new(Complex64::new(5.0, 6.0), Complex64::new(7.0, 8.0));
        cache.store_complex_vector(complex_vector_id1, value1);
        cache.store_complex_vector(complex_vector_id2, value2);

        assert_eq!(cache.get_complex_vector(complex_vector_id1), value1);
        assert_eq!(cache.get_complex_vector(complex_vector_id2), value2);
        assert_eq!(cache.get_complex_vector(complex_vector_id3), value1);
    }

    #[test]
    fn test_cache_matrix_operations() {
        let mut resources = Resources::default();

        let matrix_id1: MatrixID<2, 2> = resources.register_matrix(Some("test_matrix"));
        let matrix_id2: MatrixID<2, 2> = resources.register_matrix(None);
        let matrix_id3: MatrixID<2, 2> = resources.register_matrix(Some("test_matrix"));

        resources.reserve_cache(1);
        let cache = &mut resources.caches[0];

        let value1 = Matrix2::new(1.0, 2.0, 3.0, 4.0);
        let value2 = Matrix2::new(5.0, 6.0, 7.0, 8.0);
        cache.store_matrix(matrix_id1, value1);
        cache.store_matrix(matrix_id2, value2);

        assert_eq!(cache.get_matrix(matrix_id1), value1);
        assert_eq!(cache.get_matrix(matrix_id2), value2);
        assert_eq!(cache.get_matrix(matrix_id3), value1);
    }

    #[test]
    fn test_cache_complex_matrix_operations() {
        let mut resources = Resources::default();

        let complex_matrix_id1: ComplexMatrixID<2, 2> =
            resources.register_complex_matrix(Some("test_complex_matrix"));
        let complex_matrix_id2: ComplexMatrixID<2, 2> = resources.register_complex_matrix(None);
        let complex_matrix_id3: ComplexMatrixID<2, 2> =
            resources.register_complex_matrix(Some("test_complex_matrix"));

        resources.reserve_cache(1);
        let cache = &mut resources.caches[0];

        let value1 = Matrix2::new(
            Complex64::new(1.0, 2.0),
            Complex64::new(3.0, 4.0),
            Complex64::new(5.0, 6.0),
            Complex64::new(7.0, 8.0),
        );
        let value2 = Matrix2::new(
            Complex64::new(9.0, 10.0),
            Complex64::new(11.0, 12.0),
            Complex64::new(13.0, 14.0),
            Complex64::new(15.0, 16.0),
        );
        cache.store_complex_matrix(complex_matrix_id1, value1);
        cache.store_complex_matrix(complex_matrix_id2, value2);

        assert_eq!(cache.get_complex_matrix(complex_matrix_id1), value1);
        assert_eq!(cache.get_complex_matrix(complex_matrix_id2), value2);
        assert_eq!(cache.get_complex_matrix(complex_matrix_id3), value1);
    }

    #[test]
    fn test_uninit_parameter_registration() {
        let mut resources = Resources::default();
        let result = resources.register_parameter(&Parameter::default());
        assert!(result.is_err());
    }

    #[test]
    fn test_duplicate_named_amplitude_registration_error() {
        let mut resources = Resources::default();
        assert!(resources.register_amplitude("test_amp").is_ok());
        assert!(resources.register_amplitude("test_amp").is_err());
    }
}