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
//! Symbolic characters as algebraic integers that are sums of unity roots.

use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Add, Mul, MulAssign, Neg, Sub};

use approx;
use derive_builder::Builder;
use indexmap::{IndexMap, IndexSet};
use num::Complex;
use num_traits::{ToPrimitive, Zero};
use serde::{Deserialize, Serialize};

use crate::auxiliary::misc::HashableFloat;
use crate::chartab::unityroot::UnityRoot;

type F = fraction::GenericFraction<u32>;

#[cfg(test)]
#[path = "character_tests.rs"]
mod character_tests;

// ==================
// Struct definitions
// ==================

/// Structure to represent algebraic group characters.
///
/// Partial orders between characters are based on their complex moduli and
/// phases in the interval $`[0, 2\pi)`$ with $`0`$ being the smallest.
#[derive(Builder, Clone, Serialize, Deserialize)]
pub struct Character {
    /// The unity roots and their multiplicities constituting this character.
    #[builder(setter(custom))]
    terms: IndexMap<UnityRoot, usize>,

    /// A threshold for approximate partial ordering comparisons.
    #[builder(setter(custom), default = "1e-14")]
    threshold: f64,
}

impl CharacterBuilder {
    fn terms(&mut self, ts: &[(UnityRoot, usize)]) -> &mut Self {
        let mut terms = IndexMap::<UnityRoot, usize>::new();
        // This ensures that if there are two identical unity roots in ts, their multiplicities are
        // accumulated.
        for (ur, mult) in ts.iter() {
            *terms.entry(ur.clone()).or_default() += mult;
        }
        self.terms = Some(terms);
        self
    }

    fn threshold(&mut self, thresh: f64) -> &mut Self {
        if thresh >= 0.0 {
            self.threshold = Some(thresh);
        } else {
            log::error!(
                "Threshold value {} is invalid. Threshold must be non-negative.",
                thresh
            );
            self.threshold = None;
        }
        self
    }
}

impl Character {
    /// Returns a builder to construct a new character.
    ///
    /// # Returns
    ///
    /// A builder to construct a new character.
    fn builder() -> CharacterBuilder {
        CharacterBuilder::default()
    }

    /// Constructs a character from an array of unity roots and multiplicities.
    ///
    /// # Returns
    ///
    /// A character.
    #[must_use]
    pub fn new(ts: &[(UnityRoot, usize)]) -> Self {
        Self::builder()
            .terms(ts)
            .build()
            .expect("Unable to construct a character.")
    }

    /// Returns the threshold for approximate partial ordering comparisons.
    pub fn threshold(&self) -> f64 {
        self.threshold
    }

    /// The complex representation of this character.
    ///
    /// # Returns
    ///
    /// The complex value corresponding to this character.
    ///
    /// # Panics
    ///
    /// Panics when encountering any multiplicity that cannot be converted to `f64`.
    #[must_use]
    pub fn complex_value(&self) -> Complex<f64> {
        self.terms
            .iter()
            .filter_map(|(uroot, &mult)| {
                if mult > 0 {
                    Some(
                        uroot.complex_value()
                            * mult
                                .to_f64()
                                .unwrap_or_else(|| panic!("Unable to convert `{mult}` to `f64`.")),
                    )
                } else {
                    None
                }
            })
            .sum()
    }

    /// Gets a numerical form for this character, nicely formatted up to a
    /// required precision.
    ///
    /// # Arguments
    ///
    /// * `precision` - The number of decimal places.
    ///
    /// # Returns
    ///
    /// The formatted numerical form.
    #[must_use]
    pub fn get_numerical(&self, real_only: bool, precision: usize) -> String {
        let Complex { re, im } = self.complex_value();
        if real_only {
            format!("{:+.precision$}", {
                if approx::relative_eq!(
                    re,
                    0.0,
                    epsilon = self.threshold,
                    max_relative = self.threshold
                ) && re < 0.0
                {
                    -re
                } else {
                    re
                }
            })
        } else {
            format!(
                "{:+.precision$} {} {:.precision$}i",
                {
                    if approx::relative_eq!(
                        re,
                        0.0,
                        epsilon = self.threshold,
                        max_relative = self.threshold
                    ) && re < 0.0
                    {
                        -re
                    } else {
                        re
                    }
                },
                {
                    if im >= 0.0
                        || approx::relative_eq!(
                            im,
                            0.0,
                            epsilon = self.threshold,
                            max_relative = self.threshold
                        )
                    {
                        "+"
                    } else {
                        "-"
                    }
                },
                im.abs()
            )
        }
    }

    /// Gets the concise form for this character.
    ///
    /// The concise form shows an integer or an integer followed by $`i`$ if the character is
    /// purely integer or integer imaginary. Otherwise, the concise form is either the analytic
    /// form of the character showing all contributing unity roots and their multiplicities, or a
    /// complex number formatted to 3 d.p.
    ///
    /// # Arguments
    ///
    /// * `num_non_int` - A flag indicating of non-integers should be shown in numerical form
    /// instead of analytic.
    ///
    /// # Returns
    ///
    /// The concise form of the character.
    fn get_concise(&self, num_non_int: bool) -> String {
        let complex_value = self.complex_value();
        let precision = 3i32;
        let precision_u = usize::try_from(precision.unsigned_abs())
            .expect("Unable to represent `precision` as `usize`.");
        if approx::relative_eq!(
            complex_value.im,
            0.0,
            epsilon = 10.0f64.powi(-precision - 1).max(self.threshold),
            max_relative = 10.0f64.powi(-precision - 1).max(self.threshold)
        ) {
            // Zero imaginary
            // Zero or non-zero real
            let rounded_re = complex_value.re.round_factor(self.threshold);
            if approx::relative_eq!(
                rounded_re,
                rounded_re.round(),
                epsilon = 10.0f64.powi(-precision - 1).max(self.threshold),
                max_relative = 10.0f64.powi(-precision - 1).max(self.threshold)
            ) {
                // Integer real
                if approx::relative_eq!(
                    rounded_re,
                    0.0,
                    epsilon = 10.0f64.powi(-precision - 1).max(self.threshold),
                    max_relative = 10.0f64.powi(-precision - 1).max(self.threshold)
                ) {
                    "0".to_string()
                } else {
                    format!("{:+.0}", complex_value.re)
                }
            } else {
                // Non-integer real
                if num_non_int {
                    format!("{:+.precision_u$}", complex_value.re)
                } else {
                    format!("{self:?}")
                }
            }
        } else if approx::relative_eq!(
            complex_value.re,
            0.0,
            epsilon = self.threshold,
            max_relative = self.threshold
        ) {
            // Non-zero imaginary
            // Zero real
            let rounded_im = complex_value.im.round_factor(self.threshold);
            if approx::relative_eq!(
                rounded_im,
                rounded_im.round(),
                epsilon = 10.0f64.powi(-precision - 1).max(self.threshold),
                max_relative = 10.0f64.powi(-precision - 1).max(self.threshold)
            ) {
                // Integer imaginary
                if approx::relative_eq!(
                    rounded_im.abs(),
                    1.0,
                    epsilon = 10.0f64.powi(-precision - 1).max(self.threshold),
                    max_relative = 10.0f64.powi(-precision - 1).max(self.threshold)
                ) {
                    // i or -i
                    let imag = if rounded_im > 0.0 { "+i" } else { "-i" };
                    imag.to_string()
                } else {
                    // ki
                    format!("{:+.0}i", complex_value.im)
                }
            } else {
                // Non-integer imaginary
                if num_non_int {
                    format!("{:+.precision_u$}i", complex_value.im)
                } else {
                    format!("{self:?}")
                }
            }
        } else {
            // Non-zero imaginary
            // Non-zero real
            let rounded_re = complex_value.re.round_factor(self.threshold);
            let rounded_im = complex_value.im.round_factor(self.threshold);
            if (approx::relative_ne!(
                rounded_re,
                rounded_re.round(),
                epsilon = 10.0f64.powi(-precision - 1).max(self.threshold),
                max_relative = 10.0f64.powi(-precision - 1).max(self.threshold)
            ) || approx::relative_ne!(
                rounded_im,
                rounded_im.round(),
                epsilon = 10.0f64.powi(-precision - 1).max(self.threshold),
                max_relative = 10.0f64.powi(-precision - 1).max(self.threshold)
            )) && !num_non_int
            {
                format!("{self:?}")
            } else {
                format!(
                    "{:+.precision_u$} {} {:.precision_u$}i",
                    complex_value.re,
                    {
                        if complex_value.im > 0.0 {
                            "+"
                        } else {
                            "-"
                        }
                    },
                    complex_value.im.abs()
                )
            }
        }
    }

    /// Gets the simplified form for this character.
    ///
    /// The simplified form gathers terms whose unity roots differ from each other by a factor of
    /// $`-1`$.
    ///
    /// # Returns
    ///
    /// The simplified form of the character.
    ///
    /// # Panics
    ///
    /// Panics when the multiplicity of any unitary root cannot be retrieved.
    #[must_use]
    pub fn simplify(&self) -> Self {
        let mut urs: IndexSet<_> = self.terms.keys().rev().collect();
        let mut simplified_terms = Vec::<(UnityRoot, usize)>::with_capacity(urs.len());
        let f12 = F::new(1u32, 2u32);
        while !urs.is_empty() {
            let ur = urs
                .pop()
                .expect("Unable to retrieve an unexamined unity root.");
            let nur_option = urs
                .iter()
                .find(|&test_ur| {
                    test_ur.fraction == ur.fraction + f12 || test_ur.fraction == ur.fraction - f12
                })
                .copied();
            if let Some(nur) = nur_option {
                let res = urs.shift_remove(nur);
                debug_assert!(res);
                let ur_mult = self
                    .terms
                    .get(ur)
                    .unwrap_or_else(|| panic!("Unable to retrieve the multiplicity of {ur}."));
                let nur_mult = self
                    .terms
                    .get(nur)
                    .unwrap_or_else(|| panic!("Unable to retrieve the multiplicity of {nur}."));
                match ur_mult.cmp(nur_mult) {
                    Ordering::Less => simplified_terms.push((nur.clone(), nur_mult - ur_mult)),
                    Ordering::Greater => simplified_terms.push((ur.clone(), ur_mult - nur_mult)),
                    Ordering::Equal => (),
                };
            } else {
                let ur_mult = self
                    .terms
                    .get(ur)
                    .unwrap_or_else(|| panic!("Unable to retrieve the multiplicity of {ur}."));
                simplified_terms.push((ur.clone(), *ur_mult));
            }
        }
        Character::builder()
            .terms(&simplified_terms)
            .threshold(self.threshold)
            .build()
            .expect("Unable to construct a simplified character.")
    }

    /// The complex conjugate of this character.
    ///
    /// # Returns
    ///
    /// The complex conjugate of this character.
    ///
    /// # Panics
    ///
    /// Panics when the complex conjugate cannot be found.
    #[must_use]
    pub fn complex_conjugate(&self) -> Self {
        Self::builder()
            .terms(
                &self
                    .terms
                    .iter()
                    .map(|(ur, mult)| (ur.complex_conjugate(), *mult))
                    .collect::<Vec<_>>(),
            )
            .threshold(self.threshold)
            .build()
            .unwrap_or_else(|_| panic!("Unable to construct the complex conjugate of `{self}`."))
    }
}

// =====================
// Trait implementations
// =====================

impl PartialEq for Character {
    fn eq(&self, other: &Self) -> bool {
        (self.terms == other.terms) || {
            let self_complex = self.complex_value();
            let other_complex = other.complex_value();
            let thresh = (self.threshold * other.threshold).sqrt();
            approx::relative_eq!(
                self_complex.re,
                other_complex.re,
                epsilon = thresh,
                max_relative = thresh
            ) && approx::relative_eq!(
                self_complex.im,
                other_complex.im,
                epsilon = thresh,
                max_relative = thresh
            )
        }
    }
}

impl Eq for Character {}

impl PartialOrd for Character {
    /// Two characters are compared based on their constituent unity roots.
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        let mut self_terms = self.terms.clone();
        self_terms.retain(|_, mult| *mult > 0);
        self_terms.sort_by(|uroot1, _, uroot2, _| {
            uroot1
                .partial_cmp(uroot2)
                .unwrap_or_else(|| panic!("{uroot1} and {uroot2} cannot be compared."))
        });

        let mut other_terms = other.terms.clone();
        other_terms.retain(|_, mult| *mult > 0);
        other_terms.sort_by(|uroot1, _, uroot2, _| {
            uroot1
                .partial_cmp(uroot2)
                .unwrap_or_else(|| panic!("{uroot1} and {uroot2} cannot be compared."))
        });

        let self_terms_vec = self_terms.into_iter().collect::<Vec<_>>();
        let other_terms_vec = other_terms.into_iter().collect::<Vec<_>>();
        self_terms_vec.partial_cmp(&other_terms_vec)
    }
}

impl fmt::Debug for Character {
    /// Prints the full form for this character showing all contributing unity
    /// roots and their multiplicities.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let one = UnityRoot::new(0u32, 2u32);
        let str_terms: Vec<String> = self
            .terms
            .clone()
            .sorted_by(|k1, _, k2, _| {
                k1.partial_cmp(k2)
                    .unwrap_or_else(|| panic!("{k1} and {k2} cannot be compared."))
            })
            .filter_map(|(root, mult)| {
                if mult == 1 {
                    Some(format!("{root}"))
                } else if mult == 0 {
                    None
                } else if root == one {
                    Some(format!("{mult}"))
                } else {
                    Some(format!("{mult}*{root}"))
                }
            })
            .collect();
        if str_terms.is_empty() {
            write!(f, "0")
        } else {
            write!(f, "{}", str_terms.join(" + "))
        }
    }
}

impl fmt::Display for Character {
    /// Prints the short form for this character that shows either an integer
    /// or an imaginary integer or a compact complex number at 3 d.p.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.get_concise(false))
    }
}

impl Hash for Character {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let terms_vec = self
            .terms
            .clone()
            .sorted_by(|ur1, m1, ur2, m2| {
                PartialOrd::partial_cmp(&(ur1.clone(), m1), &(ur2.clone(), m2)).unwrap_or_else(
                    || {
                        panic!(
                            "{:?} anmd {:?} cannot be compared.",
                            (ur1.clone(), m1),
                            (ur2.clone(), m2)
                        )
                    },
                )
            })
            .collect::<Vec<_>>();
        terms_vec.hash(state);
    }
}

// ----
// Zero
// ----
impl Zero for Character {
    fn zero() -> Self {
        Self::new(&[])
    }

    fn is_zero(&self) -> bool {
        *self == Self::zero()
    }
}

// ---
// Add
// ---
impl Add<&'_ Character> for &Character {
    type Output = Character;

    fn add(self, rhs: &Character) -> Self::Output {
        let mut sum = self.clone();
        for (ur, mult) in rhs.terms.iter() {
            *sum.terms.entry(ur.clone()).or_default() += mult;
        }
        sum
    }
}

impl Add<&'_ Character> for Character {
    type Output = Character;

    fn add(self, rhs: &Self) -> Self::Output {
        &self + rhs
    }
}

impl Add<Character> for &Character {
    type Output = Character;

    fn add(self, rhs: Character) -> Self::Output {
        self + &rhs
    }
}

impl Add<Character> for Character {
    type Output = Character;

    fn add(self, rhs: Self) -> Self::Output {
        &self + &rhs
    }
}

// ---
// Neg
// ---
impl Neg for &Character {
    type Output = Character;

    fn neg(self) -> Self::Output {
        let f12 = F::new(1u32, 2u32);
        let terms: IndexMap<_, _> = self
            .terms
            .iter()
            .map(|(ur, mult)| {
                let mut nur = ur.clone();
                nur.fraction = (nur.fraction + f12).fract();
                (nur, *mult)
            })
            .collect();
        let mut nchar = self.clone();
        nchar.terms = terms;
        nchar
    }
}

impl Neg for Character {
    type Output = Character;

    fn neg(self) -> Self::Output {
        -&self
    }
}

// ---
// Sub
// ---
impl Sub<&'_ Character> for &Character {
    type Output = Character;

    fn sub(self, rhs: &Character) -> Self::Output {
        self + (-rhs)
    }
}

impl Sub<&'_ Character> for Character {
    type Output = Character;

    fn sub(self, rhs: &Self) -> Self::Output {
        &self + (-rhs)
    }
}

impl Sub<Character> for &Character {
    type Output = Character;

    fn sub(self, rhs: Character) -> Self::Output {
        self + (-&rhs)
    }
}

impl Sub<Character> for Character {
    type Output = Character;

    fn sub(self, rhs: Self) -> Self::Output {
        &self + (-&rhs)
    }
}

// ---------
// MulAssign
// ---------
impl MulAssign<usize> for Character {
    fn mul_assign(&mut self, rhs: usize) {
        self.terms.iter_mut().for_each(|(_, mult)| {
            *mult *= rhs;
        });
    }
}

// ---
// Mul
// ---
impl Mul<usize> for &Character {
    type Output = Character;

    fn mul(self, rhs: usize) -> Self::Output {
        let mut prod = self.clone();
        prod *= rhs;
        prod
    }
}

impl Mul<usize> for Character {
    type Output = Character;

    fn mul(self, rhs: usize) -> Self::Output {
        &self * rhs
    }
}