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
//! Abstract group structures.

use std::fmt;
use std::hash::Hash;
use std::ops::Mul;

use anyhow::{self, format_err};
use derive_builder::Builder;
use indexmap::IndexSet;
use log;
use ndarray::{Array2, Zip};
use num::Integer;
use num_traits::Inv;
use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::chartab::chartab_group::CharacterProperties;
use crate::chartab::chartab_symbols::{
    CollectionSymbol, LinearSpaceSymbol, ReducibleLinearSpaceSymbol,
};
use crate::chartab::{CharacterTable, CorepCharacterTable, RepCharacterTable};
use crate::group::class::{ClassProperties, EagerClassStructure};

pub mod class;

// =================
// Trait definitions
// =================

/// Trait for order finiteness of group elements.
pub trait FiniteOrder {
    /// The integer type for the order of the element.
    type Int: Integer;

    /// Returns the finite order of the element.
    fn order(&self) -> Self::Int;
}

/// Trait for purely group-theoretic properties.
pub trait GroupProperties
where
    Self::GroupElement: Mul<Output = Self::GroupElement>
        + Inv<Output = Self::GroupElement>
        + Hash
        + Eq
        + Clone
        + Sync
        + fmt::Debug
        + FiniteOrder,
{
    /// The type of the elements in the group.
    type GroupElement;
    type ElementCollection: Clone + IntoIterator<Item = Self::GroupElement>;

    /// Returns the name of the group.
    fn name(&self) -> String;

    /// Returns the finite subgroup name of this group, if any.
    fn finite_subgroup_name(&self) -> Option<&String>;

    /// Returns an iterable collection of the elements in the group.
    fn elements(&self) -> &Self::ElementCollection;

    /// Given an index, returns the element associated with it, or `None` if the index is out of
    /// range.
    fn get_index(&self, index: usize) -> Option<Self::GroupElement>;

    /// Given an element, returns its index in the group, or `None` if the element does not exist
    /// in the group.
    fn get_index_of(&self, g: &Self::GroupElement) -> Option<usize>;

    /// Checks if an element is a member of the group.
    fn contains(&self, g: &Self::GroupElement) -> bool;

    /// Checks if this group is abelian.
    fn is_abelian(&self) -> bool;

    /// Returns the order of the group.
    fn order(&self) -> usize;

    /// Returns the Cayley table of the group, if any.
    fn cayley_table(&self) -> Option<&Array2<usize>>;
}

/// Trait for indicating that a group can be partitioned into a unitary halving subgroup and and
/// antiunitary coset.
pub trait HasUnitarySubgroup: GroupProperties
where
    Self::UnitarySubgroup: GroupProperties<GroupElement = Self::GroupElement> + CharacterProperties,
{
    /// The type of the unitary halving subgroup.
    type UnitarySubgroup;

    /// Returns a shared reference to the unitary subgroup associated with this group.
    fn unitary_subgroup(&self) -> &Self::UnitarySubgroup;

    /// Checks if an element in the group belongs to the antiunitary coset.
    ///
    /// # Arguments
    ///
    /// * `element` - A group element.
    ///
    /// # Returns
    ///
    /// Returns `true` if `element` is in the antiunitary coset of the group.
    ///
    /// # Panics
    ///
    /// Panics if `element` is not a member of the group.
    fn check_elem_antiunitary(&self, element: &Self::GroupElement) -> bool;
}

// ====================================
// Enum definitions and implementations
// ====================================

/// Enumerated type for the type of a group.
#[derive(Clone, Hash, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum GroupType {
    /// Variant for an ordinary group which contains no time-reversed operations.
    ///
    /// The associated boolean indicates whether this group is a double group or not.
    Ordinary(bool),

    /// Variant for a magnetic grey group which contains the time-reversal operation.
    ///
    /// The associated boolean indicates whether this group is a double group or not.
    MagneticGrey(bool),

    /// Variant for a magnetic black and white group which contains time-reversed operations, but
    /// not the time-reversal operation itself.
    ///
    /// The associated boolean indicates whether this group is a double group or not.
    MagneticBlackWhite(bool),
}

impl fmt::Display for GroupType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Ordinary(true) => write!(f, "Double ordinary group"),
            Self::Ordinary(false) => write!(f, "Ordinary group"),
            Self::MagneticGrey(true) => write!(f, "Double magnetic grey group"),
            Self::MagneticGrey(false) => write!(f, "Magnetic grey group"),
            Self::MagneticBlackWhite(true) => write!(f, "Double magnetic black-and-white group"),
            Self::MagneticBlackWhite(false) => write!(f, "Magnetic black-and-white group"),
        }
    }
}

/// Ordinary group.
pub const ORGRP: GroupType = GroupType::Ordinary(false);

/// Ordinary double group.
pub const ORGRP2: GroupType = GroupType::Ordinary(true);

/// Black-and-white magnetic group.
pub const BWGRP: GroupType = GroupType::MagneticBlackWhite(false);

/// Black-and-white magnetic double group.
pub const BWGRP2: GroupType = GroupType::MagneticBlackWhite(true);

/// Grey magnetic group.
pub const GRGRP: GroupType = GroupType::MagneticGrey(false);

/// Grey magnetic double group.
pub const GRGRP2: GroupType = GroupType::MagneticGrey(true);

// ======================================
// Struct definitions and implementations
// ======================================

// --------------
// Abstract group
// --------------

/// Structure for managing abstract groups eagerly, *i.e.* all group elements are stored.
#[derive(Builder, Clone, Serialize, Deserialize)]
pub struct EagerGroup<T>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
{
    /// A name for the abstract group.
    name: String,

    /// An ordered hashset containing the elements of the group.
    #[builder(setter(custom))]
    elements: IndexSet<T>,

    /// The Cayley table for this group w.r.t. the elements in [`Self::elements`].
    ///
    /// Elements are multiplied left-to-right, with functions written on the right.
    /// Row elements are on the left, column elements on the right.  So column
    /// elements act on the function first, followed by row elements.
    ///
    /// Each element in this array contains the index of the resultant operation
    /// from the composition, w.r.t. the ordered hashset [`Self::elements`].
    #[builder(setter(skip), default = "None")]
    cayley_table: Option<Array2<usize>>,
}

impl<T> EagerGroupBuilder<T>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    for<'a, 'b> &'b T: Mul<&'a T, Output = T>,
{
    fn elements(&mut self, elems: Vec<T>) -> &mut Self {
        self.elements = Some(elems.into_iter().collect());
        self
    }

    fn elements_iter(&mut self, elems_iter: impl Iterator<Item = T>) -> &mut Self {
        self.elements = Some(elems_iter.collect());
        self
    }
}

impl<T> EagerGroup<T>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    for<'a, 'b> &'b T: Mul<&'a T, Output = T>,
{
    /// Returns a builder to construct a new abstract group.
    ///
    /// # Returns
    ///
    /// A builder to construct a new abstract group.
    ///
    /// # Panics
    ///
    /// Panics if the group fails to be constructed.
    fn builder() -> EagerGroupBuilder<T> {
        EagerGroupBuilder::<T>::default()
    }

    /// Constructs an abstract group from its elements and calculate its Cayley table.
    ///
    /// # Arguments
    ///
    /// * `name` - A name to be given to the abstract group.
    /// * `elements` - A vector of *all* group elements.
    ///
    /// # Returns
    ///
    /// An abstract group with its Cayley table constructed.
    ///
    /// # Panics
    ///
    /// Panics if the group fails to be constructed.
    ///
    /// # Errors
    ///
    /// Errors if the Cayley table fails to be constructed.
    pub fn new(name: &str, elements: Vec<T>) -> Result<Self, anyhow::Error> {
        let mut group = Self::builder()
            .name(name.to_string())
            .elements(elements)
            .build()
            .expect("Unable to construct a group.");
        group.compute_cayley_table()?;
        Ok(group)
    }

    /// Constructs an abstract group from its elements but without calculating its Cayley table.
    ///
    /// # Arguments
    ///
    /// * `name` - A name to be given to the abstract group.
    /// * `elements` - A vector of *all* group elements.
    ///
    /// # Returns
    ///
    /// An abstract group without its Cayley table constructed.
    pub fn new_no_ctb(name: &str, elements: Vec<T>) -> Self {
        Self::builder()
            .name(name.to_string())
            .elements(elements)
            .build()
            .expect("Unable to construct a group.")
    }

    /// Constructs an abstract group from an iterator of its elements and calculate its Cayley
    /// table.
    ///
    /// # Arguments
    ///
    /// * `name` - A name to be given to the abstract group.
    /// * `elements_iter` - An iterator yielding group elements.
    ///
    /// # Returns
    ///
    /// An abstract group with its Cayley table constructed.
    ///
    /// # Panics
    ///
    /// Panics if the group fails to be constructed.
    ///
    /// # Errors
    ///
    /// Errors if the Cayley table fails to be constructed.
    pub fn from_iter(
        name: &str,
        elements_iter: impl Iterator<Item = T>,
    ) -> Result<Self, anyhow::Error> {
        let mut group = Self::builder()
            .name(name.to_string())
            .elements_iter(elements_iter)
            .build()
            .expect("Unable to construct a group.");
        group.compute_cayley_table()?;
        Ok(group)
    }

    /// Constructs an abstract group from an iterator of its elements but without calculating its
    /// Cayley table.
    ///
    /// # Arguments
    ///
    /// * `name` - A name to be given to the abstract group.
    /// * `elements_iter` - An iterator yielding group elements.
    ///
    /// # Panics
    ///
    /// Panics if the group fails to be constructed.
    ///
    /// # Returns
    ///
    /// An abstract group without its Cayley table constructed.
    pub fn from_iter_no_ctb(name: &str, elements_iter: impl Iterator<Item = T>) -> Self {
        Self::builder()
            .name(name.to_string())
            .elements_iter(elements_iter)
            .build()
            .expect("Unable to construct a group.")
    }

    /// Constructs the Cayley table for the abstract group.
    ///
    /// # Errors
    ///
    /// Errors if the Cayley table fails to be constructed.
    fn compute_cayley_table(&mut self) -> Result<(), anyhow::Error> {
        log::debug!("Constructing Cayley table in parallel...");
        let mut ctb = Array2::<usize>::zeros((self.order(), self.order()));
        Zip::indexed(&mut ctb).par_map_collect(|(i, j), k| {
            let op_i_ref = self.elements
                .get_index(i)
                .ok_or_else(|| format_err!("Element with index {i} cannot be retrieved."))?;
            let op_j_ref = self.elements
                .get_index(j)
                .ok_or_else(|| format_err!("Element with index {j} cannot be retrieved."))?;
            let op_k = op_i_ref * op_j_ref;
            *k = self.elements
                .get_index_of(&op_k)
                .ok_or_else(||
                    format_err!("Group closure not fulfilled. The composition {:?} * {:?} = {:?} is not contained in the group. Try relaxing distance thresholds.",
                        op_i_ref,
                        op_j_ref,
                        &op_k)
                    )?;
            Ok::<(), anyhow::Error>(())
        }).into_iter().collect::<Result<(), anyhow::Error>>()?;
        self.cayley_table = Some(ctb);
        log::debug!("Constructing Cayley table in parallel... Done.");
        Ok(())
    }
}

impl<T> GroupProperties for EagerGroup<T>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    for<'a, 'b> &'b T: Mul<&'a T, Output = T>,
{
    type GroupElement = T;
    type ElementCollection = IndexSet<T>;

    fn name(&self) -> String {
        self.name.to_string()
    }

    fn finite_subgroup_name(&self) -> Option<&String> {
        None
    }

    fn get_index(&self, index: usize) -> Option<Self::GroupElement> {
        self.elements.get_index(index).cloned()
    }

    fn get_index_of(&self, g: &Self::GroupElement) -> Option<usize> {
        self.elements.get_index_of(g)
    }

    fn contains(&self, g: &Self::GroupElement) -> bool {
        self.elements.contains(g)
    }

    fn elements(&self) -> &Self::ElementCollection {
        &self.elements
    }

    fn is_abelian(&self) -> bool {
        if let Some(ctb) = &self.cayley_table {
            ctb == ctb.t()
        } else {
            self.elements.iter().enumerate().all(|(i, gi)| {
                (0..i).all(|j| {
                    let gj = self
                        .elements
                        .get_index(j)
                        .unwrap_or_else(|| panic!("Element with index `{j}` not found."));
                    gi * gj == gj * gi
                })
            })
        }
    }

    fn order(&self) -> usize {
        self.elements.len()
    }

    fn cayley_table(&self) -> Option<&Array2<usize>> {
        self.cayley_table.as_ref()
    }
}

// -------------------------
// Unitary-represented group
// -------------------------

/// Structure for managing groups with unitary representations.
#[derive(Clone, Builder, Serialize, Deserialize)]
pub struct UnitaryRepresentedGroup<T, RowSymbol, ColSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    RowSymbol: LinearSpaceSymbol,
    ColSymbol: CollectionSymbol<CollectionElement = T>,
{
    /// A name for the unitary-represented group.
    name: String,

    /// An optional name if this unitary group is actually a finite subgroup of an infinite
    /// group [`Self::name`].
    #[builder(setter(custom), default = "None")]
    finite_subgroup_name: Option<String>,

    /// The underlying abstract group of this unitary-represented group.
    abstract_group: EagerGroup<T>,

    /// The class structure of this unitary-represented group that is induced by the following
    /// equivalence relation:
    ///
    /// ```math
    ///     g \sim h \Leftrightarrow \exists u : h = u g u ^{-1}.
    /// ```
    #[builder(setter(skip), default = "None")]
    class_structure: Option<EagerClassStructure<T, ColSymbol>>,

    /// The character table for the irreducible representations of this group.
    #[builder(setter(skip), default = "None")]
    pub(crate) irrep_character_table: Option<RepCharacterTable<RowSymbol, ColSymbol>>,
}

impl<T, RowSymbol, ColSymbol> UnitaryRepresentedGroupBuilder<T, RowSymbol, ColSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    for<'a, 'b> &'b T: Mul<&'a T, Output = T>,
    RowSymbol: LinearSpaceSymbol,
    ColSymbol: CollectionSymbol<CollectionElement = T>,
{
    fn finite_subgroup_name(&mut self, name_opt: Option<String>) -> &mut Self {
        if name_opt.is_some() {
            if self.name.as_ref().expect("Group name not found.").clone() == *"O(3)"
                || self
                    .name
                    .as_ref()
                    .expect("Group name not found.")
                    .contains('∞')
            {
                self.finite_subgroup_name = Some(name_opt);
            } else {
                panic!(
                    "Setting a finite subgroup name for a non-infinite group is not supported yet."
                )
            }
        }
        self
    }
}

impl<T, RowSymbol, ColSymbol> UnitaryRepresentedGroup<T, RowSymbol, ColSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    RowSymbol: LinearSpaceSymbol,
    ColSymbol: CollectionSymbol<CollectionElement = T>,
{
    /// Sets the finite subgroup name of this group.
    ///
    /// # Arguments
    ///
    /// * `name` - A name to be set as the finite subgroup name of this group.
    pub(crate) fn set_finite_subgroup_name(&mut self, name: Option<String>) {
        self.finite_subgroup_name = name;
    }
}

impl<T, RowSymbol, ColSymbol> UnitaryRepresentedGroup<T, RowSymbol, ColSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    for<'a, 'b> &'b T: Mul<&'a T, Output = T>,
    RowSymbol: LinearSpaceSymbol,
    ColSymbol: CollectionSymbol<CollectionElement = T>,
{
    /// Returns a builder to construct a new unitary-represented group.
    ///
    /// # Returns
    ///
    /// A builder to construct a new unitary-represented group.
    fn builder() -> UnitaryRepresentedGroupBuilder<T, RowSymbol, ColSymbol> {
        UnitaryRepresentedGroupBuilder::<T, RowSymbol, ColSymbol>::default()
    }

    /// Constructs a unitary-represented group from its elements.
    ///
    /// # Arguments
    ///
    /// * `name` - A name to be given to the unitary-represented group.
    /// * `elements` - A vector of *all* group elements.
    ///
    /// # Returns
    ///
    /// A unitary-represented group with its Cayley table constructed and conjugacy classes
    /// determined.
    pub fn new(name: &str, elements: Vec<T>) -> Result<Self, anyhow::Error> {
        let abstract_group = EagerGroup::<T>::new(name, elements);
        let mut unitary_group = UnitaryRepresentedGroup::<T, RowSymbol, ColSymbol>::builder()
            .name(name.to_string())
            .abstract_group(abstract_group?)
            .build()
            .expect("Unable to construct a unitary group.");
        unitary_group.compute_class_structure()?;
        Ok(unitary_group)
    }
}

impl<T, RowSymbol, ColSymbol> GroupProperties for UnitaryRepresentedGroup<T, RowSymbol, ColSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    for<'a, 'b> &'b T: Mul<&'a T, Output = T>,
    RowSymbol: LinearSpaceSymbol,
    ColSymbol: CollectionSymbol<CollectionElement = T>,
{
    type GroupElement = T;
    type ElementCollection = IndexSet<Self::GroupElement>;

    fn name(&self) -> String {
        self.name.to_string()
    }

    fn finite_subgroup_name(&self) -> Option<&String> {
        self.finite_subgroup_name.as_ref()
    }

    fn get_index(&self, index: usize) -> Option<Self::GroupElement> {
        self.abstract_group.get_index(index)
    }

    fn get_index_of(&self, g: &Self::GroupElement) -> Option<usize> {
        self.abstract_group.get_index_of(g)
    }

    fn contains(&self, g: &Self::GroupElement) -> bool {
        self.abstract_group.contains(g)
    }

    fn elements(&self) -> &Self::ElementCollection {
        self.abstract_group.elements()
    }

    fn is_abelian(&self) -> bool {
        self.abstract_group.is_abelian()
    }

    fn order(&self) -> usize {
        self.abstract_group.order()
    }

    fn cayley_table(&self) -> Option<&Array2<usize>> {
        self.abstract_group.cayley_table()
    }
}

// --------------------------
// Magnetic-represented group
// --------------------------

/// Structure for managing groups with magnetic corepresentations.
///
/// Such a group consists of two types of elements in equal numbers: those that are unitary
/// represented and those that are antiunitary represented. This division of elements affects the
/// class structure of the group via an equivalence relation defined in
/// Newmarch, J. D. & Golding, R. M. The character table for the corepresentations of magnetic
/// groups. *Journal of Mathematical Physics* **23**, 695–704 (1982),
/// [DOI](http://aip.scitation.org/doi/10.1063/1.525423).
#[derive(Clone, Builder, Serialize, Deserialize)]
pub struct MagneticRepresentedGroup<T, UG, RowSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    RowSymbol: ReducibleLinearSpaceSymbol<Subspace = UG::RowSymbol>,
    UG: Clone + GroupProperties<GroupElement = T> + CharacterProperties,
    <UG as ClassProperties>::ClassSymbol: Serialize + DeserializeOwned,
    CorepCharacterTable<RowSymbol, <UG as CharacterProperties>::CharTab>:
        Serialize + DeserializeOwned,
{
    /// A name for the magnetic-represented group.
    name: String,

    /// An optional name if this unitary group is actually a finite subgroup of an infinite
    /// group [`Self::name`].
    #[builder(setter(custom), default = "None")]
    finite_subgroup_name: Option<String>,

    /// The underlying abstract group of this magnetic-represented group.
    abstract_group: EagerGroup<T>,

    /// The subgroup consisting of the unitary-represented elements in the full group.
    #[builder(setter(custom))]
    unitary_subgroup: UG,

    /// The class structure of this magnetic-represented group that is induced by the following
    /// equivalence relation:
    ///
    /// ```math
    ///     g \sim h \Leftrightarrow \exists u : h = u g u^{-1} \quad \textrm{or} \quad \exists a : h = a
    ///     g^{-1} a^{-1},
    /// ```
    ///
    /// where $`u`$ is unitary-represented (*i.e.* $`u`$ is in [`Self::unitary_subgroup`]) and
    /// $`a`$ is antiunitary-represented (*i.e.* $`a`$ is not in [`Self::unitary_subgroup`]).
    #[builder(setter(skip), default = "None")]
    class_structure: Option<
        EagerClassStructure<T, <<UG as CharacterProperties>::CharTab as CharacterTable>::ColSymbol>,
    >,

    /// The character table for the irreducible corepresentations of this group.
    #[builder(setter(skip), default = "None")]
    pub(crate) ircorep_character_table: Option<CorepCharacterTable<RowSymbol, UG::CharTab>>,
}

impl<T, UG, RowSymbol> MagneticRepresentedGroupBuilder<T, UG, RowSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    for<'a, 'b> &'b T: Mul<&'a T, Output = T>,
    RowSymbol: ReducibleLinearSpaceSymbol<Subspace = UG::RowSymbol>,
    UG: Clone + GroupProperties<GroupElement = T> + CharacterProperties,
    <UG as ClassProperties>::ClassSymbol: Serialize + DeserializeOwned,
    CorepCharacterTable<RowSymbol, <UG as CharacterProperties>::CharTab>:
        Serialize + DeserializeOwned,
{
    fn finite_subgroup_name(&mut self, name_opt: Option<String>) -> &mut Self {
        if name_opt.is_some() {
            if self.name.as_ref().expect("Group name not found.").clone() == *"O(3)"
                || self
                    .name
                    .as_ref()
                    .expect("Group name not found.")
                    .contains('∞')
            {
                self.finite_subgroup_name = Some(name_opt);
            } else {
                panic!(
                    "Setting a finite subgroup name for a non-infinite group is not supported yet."
                )
            }
        }
        self
    }

    fn unitary_subgroup(&mut self, uni_subgrp: UG) -> &mut Self {
        assert!(
            uni_subgrp.elements().clone().into_iter().all(|op| self
                .abstract_group
                .as_ref()
                .expect("Abstract group not yet set for this magnetic-represented group.")
                .contains(&op)),
            "Some unitary operations cannot be found in the magnetic group."
        );
        self.unitary_subgroup = Some(uni_subgrp);
        self
    }
}

impl<T, UG, RowSymbol> MagneticRepresentedGroup<T, UG, RowSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    RowSymbol: ReducibleLinearSpaceSymbol<Subspace = UG::RowSymbol>,
    UG: Clone + GroupProperties<GroupElement = T> + CharacterProperties,
    <UG as ClassProperties>::ClassSymbol: Serialize + DeserializeOwned,
    CorepCharacterTable<RowSymbol, <UG as CharacterProperties>::CharTab>:
        Serialize + DeserializeOwned,
{
    /// Sets the finite subgroup name of this group.
    ///
    /// # Arguments
    ///
    /// * `name` - A name to be set as the finite subgroup name of this group.
    pub(crate) fn set_finite_subgroup_name(&mut self, name: Option<String>) {
        self.finite_subgroup_name = name;
    }

    /// Returns a shared reference to the unitary subgroup of this group.
    pub fn unitary_subgroup(&self) -> &UG {
        &self.unitary_subgroup
    }
}

impl<T, UG, RowSymbol> MagneticRepresentedGroup<T, UG, RowSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    for<'a, 'b> &'b T: Mul<&'a T, Output = T>,
    RowSymbol: ReducibleLinearSpaceSymbol<Subspace = UG::RowSymbol> + Serialize + DeserializeOwned,
    UG: Clone + GroupProperties<GroupElement = T> + CharacterProperties,
    <UG as ClassProperties>::ClassSymbol: Serialize + DeserializeOwned,
    <UG as CharacterProperties>::CharTab: Serialize + DeserializeOwned,
    CorepCharacterTable<RowSymbol, <UG as CharacterProperties>::CharTab>:
        Serialize + DeserializeOwned,
{
    /// Returns a builder to construct a new magnetic-represented group.
    ///
    /// # Returns
    ///
    /// A builder to construct a new magnetic-represented group.
    fn builder() -> MagneticRepresentedGroupBuilder<T, UG, RowSymbol> {
        MagneticRepresentedGroupBuilder::<T, UG, RowSymbol>::default()
    }

    /// Constructs a magnetic-represented group from its elements and the unitary subgroup.
    ///
    /// # Arguments
    ///
    /// * `name` - A name to be given to the magnetic-reprented group.
    /// * `elements` - A vector of *all* group elements.
    /// * `unitary_subgroup` - The unitary subgroup of the magnetic-represented group. All elements
    /// of this must be present in `elements`.
    ///
    /// # Returns
    ///
    /// A magnetic-represented group with its Cayley table constructed and conjugacy classes
    /// determined.
    pub fn new(name: &str, elements: Vec<T>, unitary_subgroup: UG) -> Result<Self, anyhow::Error> {
        let abstract_group = EagerGroup::<T>::new(name, elements);
        let mut magnetic_group = MagneticRepresentedGroup::<T, UG, RowSymbol>::builder()
            .name(name.to_string())
            .abstract_group(abstract_group?)
            .unitary_subgroup(unitary_subgroup)
            .build()
            .expect("Unable to construct a magnetic group.");
        magnetic_group.compute_class_structure()?;
        Ok(magnetic_group)
    }
}

impl<T, UG, RowSymbol> GroupProperties for MagneticRepresentedGroup<T, UG, RowSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    for<'a, 'b> &'b T: Mul<&'a T, Output = T>,
    RowSymbol: ReducibleLinearSpaceSymbol<Subspace = UG::RowSymbol>,
    UG: Clone + GroupProperties<GroupElement = T> + CharacterProperties,
    <UG as ClassProperties>::ClassSymbol: Serialize + DeserializeOwned,
    CorepCharacterTable<RowSymbol, <UG as CharacterProperties>::CharTab>:
        Serialize + DeserializeOwned,
{
    type GroupElement = T;
    type ElementCollection = IndexSet<T>;

    fn name(&self) -> String {
        self.name.to_string()
    }

    fn finite_subgroup_name(&self) -> Option<&String> {
        self.finite_subgroup_name.as_ref()
    }

    fn get_index(&self, index: usize) -> Option<Self::GroupElement> {
        self.abstract_group.get_index(index)
    }

    fn get_index_of(&self, g: &Self::GroupElement) -> Option<usize> {
        self.abstract_group.get_index_of(g)
    }

    fn contains(&self, g: &Self::GroupElement) -> bool {
        self.abstract_group.contains(g)
    }

    fn elements(&self) -> &Self::ElementCollection {
        self.abstract_group.elements()
    }

    fn is_abelian(&self) -> bool {
        self.abstract_group.is_abelian()
    }

    fn order(&self) -> usize {
        self.abstract_group.order()
    }

    fn cayley_table(&self) -> Option<&Array2<usize>> {
        self.abstract_group.cayley_table()
    }
}

impl<T, UG, RowSymbol> HasUnitarySubgroup for MagneticRepresentedGroup<T, UG, RowSymbol>
where
    T: Mul<Output = T> + Inv<Output = T> + Hash + Eq + Clone + Sync + fmt::Debug + FiniteOrder,
    for<'a, 'b> &'b T: Mul<&'a T, Output = T>,
    RowSymbol: ReducibleLinearSpaceSymbol<Subspace = UG::RowSymbol>,
    UG: Clone + GroupProperties<GroupElement = T> + CharacterProperties,
    <UG as ClassProperties>::ClassSymbol: Serialize + DeserializeOwned,
    CorepCharacterTable<RowSymbol, <UG as CharacterProperties>::CharTab>:
        Serialize + DeserializeOwned,
{
    type UnitarySubgroup = UG;

    fn unitary_subgroup(&self) -> &Self::UnitarySubgroup {
        &self.unitary_subgroup
    }

    /// Checks if a given element is antiunitary-represented in this group.
    ///
    /// # Arguments
    ///
    /// `element` - A reference to an element to be checked.
    ///
    /// # Returns
    ///
    /// Returns `true` if `element` is antiunitary-represented in this group.
    ///
    /// # Panics
    ///
    /// Panics if `element` is not in the group.
    fn check_elem_antiunitary(&self, element: &T) -> bool {
        if self.abstract_group.contains(element) {
            !self.unitary_subgroup.contains(element)
        } else {
            panic!("`{element:?}` is not an element of the group.")
        }
    }
}