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
//! Three-dimensional rotations of spinors.

use std::cmp;
use std::fmt;

use approx;
use factorial::Factorial;
use nalgebra::Vector3;
use ndarray::{array, Array2, Axis};
use num::{BigUint, Complex, Zero};
use num_traits::ToPrimitive;
use serde::{Deserialize, Serialize};

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

// ================
// Enum definitions
// ================

/// Enumerated type to manage spin constraints and spin space information.
#[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub enum SpinConstraint {
    /// Variant for restricted spin constraint: the spatial parts of all spin spaces are identical.
    /// The associated value is the number of spin spaces.
    Restricted(u16),

    /// Variant for unrestricted spin constraint: the spatial parts of different spin spaces are
    /// different, but spin collinearity is maintained. The associated values are the number of spin
    /// spaces (*i.e.* the number of different spatial parts that are handled separately) and a
    /// boolean indicating if the spin spaces are arranged in increasing $`m`$ order.
    Unrestricted(u16, bool),

    /// Variant for generalised spin constraint: the spatial parts of different spin spaces are
    /// different, and no spin collinearity is imposed. The associated values are the number of spin
    /// spaces and a boolean indicating if the spin spaces are arranged in increasing $`m`$ order.
    Generalised(u16, bool),
}

impl SpinConstraint {
    /// Returns the total number of units of consideration.
    ///
    /// A 'unit' of consideration is commonly known as a 'spin channel' or 'spin space'.
    pub fn nunits(&self) -> u16 {
        match self {
            Self::Restricted(nspins) => *nspins,
            Self::Unrestricted(nspins, _) => *nspins,
            Self::Generalised(_, _) => 1,
        }
    }

    /// Returns the number of spin spaces per 'unit' of consideration.
    ///
    /// A 'unit' of consideration is commonly known as a 'spin channel' or 'spin space'.
    pub fn nspins_per_unit(&self) -> u16 {
        match self {
            Self::Restricted(_) => 1,
            Self::Unrestricted(_, _) => 1,
            Self::Generalised(nspins, _) => *nspins,
        }
    }

    /// Returns the total number of spin spaces.
    pub fn nspins(&self) -> u16 {
        match self {
            Self::Restricted(nspins) => *nspins,
            Self::Unrestricted(nspins, _) => *nspins,
            Self::Generalised(nspins, _) => *nspins,
        }
    }
}

impl fmt::Display for SpinConstraint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Restricted(nspins) => write!(
                f,
                "Restricted ({} spin {})",
                nspins,
                if *nspins == 1 { "space" } else { "spaces" }
            ),
            Self::Unrestricted(nspins, increasingm) => write!(
                f,
                "Unrestricted ({} spin {}, {} m)",
                nspins,
                if *nspins == 1 { "space" } else { "spaces" },
                if *increasingm {
                    "increasing"
                } else {
                    "decreasing"
                }
            ),
            Self::Generalised(nspins, increasingm) => write!(
                f,
                "Generalised ({} spin {}, {} m)",
                nspins,
                if *nspins == 1 { "space" } else { "spaces" },
                if *increasingm {
                    "increasing"
                } else {
                    "decreasing"
                }
            ),
        }
    }
}

// =========
// Functions
// =========

/// Returns an element in the Wigner rotation matrix for $`j = 1/2`$ defined by
///
/// ```math
///     \hat{R}(\alpha, \beta, \gamma) \ket{\tfrac{1}{2}m}
///     = \sum_{m'} \ket{\tfrac{1}{2}m'} D^{(1/2)}_{m'm}(\alpha, \beta, \gamma).
/// ```
///
/// # Arguments
///
/// * `mdashi` - Index for $`m'`$ given by $`m'+\tfrac{1}{2}`$.
/// * `mi` - Index for $`m`$ given by $`m+\tfrac{1}{2}`$.
/// * `euler_angles` - A triplet of Euler angles $`(\alpha, \beta, \gamma)`$ in radians, following
/// the Whitaker convention, *i.e.* $`z_2-y-z_1`$ (extrinsic rotations).
///
/// # Returns
///
/// The element $`D^{(1/2)}_{m'm}(\alpha, \beta, \gamma)`$.
fn dmat_euler_element(mdashi: usize, mi: usize, euler_angles: (f64, f64, f64)) -> Complex<f64> {
    assert!(mdashi == 0 || mdashi == 1, "mdashi can only be 0 or 1.");
    assert!(mi == 0 || mi == 1, "mi can only be 0 or 1.");
    let (alpha, beta, gamma) = euler_angles;
    let d = if (mi, mdashi) == (1, 1) {
        // m = 1/2, mdash = 1/2
        (beta / 2.0).cos()
    } else if (mi, mdashi) == (1, 0) {
        // m = 1/2, mdash = -1/2
        (beta / 2.0).sin()
    } else if (mi, mdashi) == (0, 1) {
        // m = -1/2, mdash = 1/2
        -(beta / 2.0).sin()
    } else if (mi, mdashi) == (0, 0) {
        // m = -1/2, mdash = -1/2
        (beta / 2.0).cos()
    } else {
        panic!("Invalid mi and/or mdashi.");
    };

    let alpha_basic = alpha.rem_euclid(2.0 * std::f64::consts::PI);
    let gamma_basic = gamma.rem_euclid(2.0 * std::f64::consts::PI);
    let i = Complex::<f64>::i();
    let mut prefactor = (-i
        * (alpha_basic
            * (mdashi
                .to_f64()
                .unwrap_or_else(|| panic!("Unable to convert `{mdashi}` to `f64`."))
                - 0.5)
            + gamma_basic
                * (mi
                    .to_f64()
                    .unwrap_or_else(|| panic!("Unable to convert `{mi}` to `f64`."))
                    - 0.5)))
        .exp();

    // Half-integer j = 1/2; double-group behaviours possible.
    let alpha_double = approx::relative_eq!(
        alpha.div_euclid(2.0 * std::f64::consts::PI).rem_euclid(2.0),
        1.0,
        epsilon = 1e-14,
        max_relative = 1e-14
    );
    let gamma_double = approx::relative_eq!(
        gamma.div_euclid(2.0 * std::f64::consts::PI).rem_euclid(2.0),
        1.0,
        epsilon = 1e-14,
        max_relative = 1e-14
    );
    if alpha_double != gamma_double {
        prefactor *= -1.0;
    }
    prefactor * d
}

/// Returns the Wigner rotation matrix for $`j = 1/2`$ whose elements are defined by
///
/// ```math
/// \hat{R}(\alpha, \beta, \gamma) \ket{\tfrac{1}{2}m}
/// = \sum_{m'} \ket{\tfrac{1}{2}m'} D^{(1/2)}_{m'm}(\alpha, \beta, \gamma).
/// ```
///
/// # Arguments
///
/// * `euler_angles` - A triplet of Euler angles $`(\alpha, \beta, \gamma)`$ in radians, following
/// the Whitaker convention, *i.e.* $`z_2-y-z_1`$ (extrinsic rotations).
/// * `increasingm` - If `true`, the rows and columns of $`\mathbf{D}^{(1/2)}`$ are
/// arranged in increasing order of $`m_l = -l, \ldots, l`$. If `false`, the order is reversed:
/// $`m_l = l, \ldots, -l`$. The recommended default is `false`, in accordance with convention.
///
/// # Returns
///
/// The matrix $`\mathbf{D}^{(1/2)}(\alpha, \beta, \gamma)`$.
#[must_use]
pub fn dmat_euler(euler_angles: (f64, f64, f64), increasingm: bool) -> Array2<Complex<f64>> {
    let mut dmat = Array2::<Complex<f64>>::zeros((2, 2));
    for mdashi in 0..2 {
        for mi in 0..2 {
            dmat[(mdashi, mi)] = dmat_euler_element(mdashi, mi, euler_angles);
        }
    }
    if !increasingm {
        dmat.invert_axis(Axis(0));
        dmat.invert_axis(Axis(1));
    }
    dmat
}

/// Returns the Wigner rotation matrix for $`j = 1/2`$ whose elements are defined by
///
/// ```math
/// \hat{R}(\phi\hat{\mathbf{n}}) \ket{\tfrac{1}{2}m}
/// = \sum_{m'} \ket{\tfrac{1}{2}m'} D^{(1/2)}_{m'm}(\phi\hat{\mathbf{n}}).
/// ```
///
/// The parametrisation of $`\mathbf{D}^{(1/2)}`$ by $`\phi`$ and $`\hat{\mathbf{n}}`$ is given
/// in (**4**-9.12) of Altmann, S. L. Rotations, Quaternions, and Double Groups. (Dover
/// Publications, Inc., 2005).
///
/// # Arguments
///
/// * `angle` - The angle $`\phi`$ of the rotation in radians. A positive rotation is an
/// anticlockwise rotation when looking down `axis`.
/// * `axis` - A space-fixed vector defining the axis of rotation. The supplied vector will be
/// normalised.
/// * `increasingm` - If `true`, the rows and columns of $`\mathbf{D}^{(1/2)}`$ are
/// arranged in increasing order of $`m_l = -l, \ldots, l`$. If `false`, the order is reversed:
/// $`m_l = l, \ldots, -l`$. The recommended default is `false`, in accordance with convention.
///
/// # Returns
///
/// The matrix $`\mathbf{D}^{(1/2)}(\phi\hat{\mathbf{n}})`$.
#[must_use]
pub fn dmat_angleaxis(angle: f64, axis: Vector3<f64>, increasingm: bool) -> Array2<Complex<f64>> {
    let normalised_axis = axis.normalize();
    let nx = normalised_axis.x;
    let ny = normalised_axis.y;
    let nz = normalised_axis.z;

    let i = Complex::<f64>::i();
    let double_angle = angle.rem_euclid(4.0 * std::f64::consts::PI);
    let mut dmat = array![
        [
            (double_angle / 2.0).cos() + i * nz * (double_angle / 2.0).sin(),
            (ny - i * nx) * (double_angle / 2.0).sin()
        ],
        [
            -(ny + i * nx) * (double_angle / 2.0).sin(),
            (double_angle / 2.0).cos() - i * nz * (double_angle / 2.0).sin(),
        ]
    ];
    if !increasingm {
        dmat.invert_axis(Axis(0));
        dmat.invert_axis(Axis(1));
    }
    dmat
}

/// Returns an element in the Wigner rotation matrix for an integral or half-integral
/// $`j`$, defined by
///
/// ```math
/// \hat{R}(\alpha, \beta, \gamma) \ket{jm}
/// = \sum_{m'} \ket{jm'} D^{(j)}_{m'm}(\alpha, \beta, \gamma).
/// ```
///
/// The explicit expression for the elements of $`\mathbf{D}^{(1/2)}(\alpha, \beta, \gamma)`$
/// is given in Professor Anthony Stone's graduate lecture notes on Angular Momentum at the
/// University of Cambridge in 2006.
///
/// # Arguments
///
/// * `twoj` - Two times the angular momentum $`2j`$. If this is even, $`j`$ is integral; otherwise,
/// $`j`$ is half-integral.
/// * `mdashi` - Index for $`m'`$ given by $`m'+\tfrac{1}{2}`$.
/// * `mi` - Index for $`m`$ given by $`m+\tfrac{1}{2}`$.
/// * `euler_angles` - A triplet of Euler angles $`(\alpha, \beta, \gamma)`$ in radians, following
/// the Whitaker convention, *i.e.* $`z_2-y-z_1`$ (extrinsic rotations).
///
/// # Returns
///
/// The element $`D^{(j)}_{m'm}(\alpha, \beta, \gamma)`$.
#[allow(clippy::too_many_lines)]
pub fn dmat_euler_gen_element(
    twoj: u32,
    mdashi: usize,
    mi: usize,
    euler_angles: (f64, f64, f64),
) -> Complex<f64> {
    assert!(
        mdashi <= twoj as usize,
        "`mdashi` must be between 0 and {twoj} (inclusive).",
    );
    assert!(
        mi <= twoj as usize,
        "`mi` must be between 0 and {twoj} (inclusive).",
    );
    let (alpha, beta, gamma) = euler_angles;
    let j = f64::from(twoj) / 2.0;
    let mdash = mdashi
        .to_f64()
        .unwrap_or_else(|| panic!("Unable to convert `{mdashi}` to `f64`."))
        - j;
    let m = mi
        .to_f64()
        .unwrap_or_else(|| panic!("Unable to convert `{mi}` to `f64`."))
        - j;

    let i = Complex::<f64>::i();
    let alpha_basic = alpha.rem_euclid(2.0 * std::f64::consts::PI);
    let gamma_basic = gamma.rem_euclid(2.0 * std::f64::consts::PI);
    let mut prefactor = (-i * (alpha_basic * mdash + gamma_basic * m)).exp();

    if twoj % 2 != 0 {
        // Half-integer j; double-group behaviours possible.
        let alpha_double = approx::relative_eq!(
            alpha.div_euclid(2.0 * std::f64::consts::PI).rem_euclid(2.0),
            1.0,
            epsilon = 1e-14,
            max_relative = 1e-14
        );
        let gamma_double = approx::relative_eq!(
            gamma.div_euclid(2.0 * std::f64::consts::PI).rem_euclid(2.0),
            1.0,
            epsilon = 1e-14,
            max_relative = 1e-14
        );
        if alpha_double != gamma_double {
            prefactor *= -1.0;
        }
    }

    // tmax = min(int(j + mdash), int(j - m))
    // j + mdash = mdashi
    // j - m = twoj - mi
    let tmax = cmp::min(mdashi, twoj as usize - mi);

    // tmin = max(0, int(mdash - m))
    // mdash - m = mdashi - mi
    let tmin = if mdashi > mi { mdashi - mi } else { 0 };

    let d = (tmin..=tmax).fold(Complex::<f64>::zero(), |acc, t| {
        // j - m = twoj - mi
        // j - mdash = twoj - mdashi
        let num = (BigUint::from(mdashi)
            .checked_factorial()
            .unwrap_or_else(|| panic!("Unable to compute the factorial of {mdashi}."))
            * BigUint::from(twoj as usize - mdashi)
                .checked_factorial()
                .unwrap_or_else(|| {
                    panic!(
                        "Unable to compute the factorial of {}.",
                        twoj as usize - mdashi
                    )
                })
            * BigUint::from(mi)
                .checked_factorial()
                .unwrap_or_else(|| panic!("Unable to compute the factorial of {mi}."))
            * BigUint::from(twoj as usize - mi)
                .checked_factorial()
                .unwrap_or_else(|| {
                    panic!("Unable to compute the factorial of {}.", twoj as usize - mi)
                }))
        .to_f64()
        .expect("Unable to convert a `BigUint` value to `f64`.")
        .sqrt();

        // t <= j + mdash ==> j + mdash - t = mdashi - t >= 0
        // t <= j - m ==> j - m - t = twoj - mi - t >= 0
        // t >= 0
        // t >= mdash - m ==> t - (mdash - m) = t + mi - mdashi >= 0
        let den = (BigUint::from(mdashi - t)
            .checked_factorial()
            .unwrap_or_else(|| panic!("Unable to compute the factorial of {}.", mdashi - t))
            * BigUint::from(twoj as usize - mi - t)
                .checked_factorial()
                .unwrap_or_else(|| {
                    panic!(
                        "Unable to compute the factorial of {}.",
                        twoj as usize - mi - t
                    )
                })
            * BigUint::from(t)
                .checked_factorial()
                .unwrap_or_else(|| panic!("Unable to compute the factorial of {t}."))
            * BigUint::from(t + mi - mdashi)
                .checked_factorial()
                .unwrap_or_else(|| {
                    panic!("Unable to compute the factorial of {}.", t + mi - mdashi)
                }))
        .to_f64()
        .expect("Unable to convert a `BigUint` value to `f64`.");

        let trigfactor = (beta / 2.0).cos().powi(
            i32::try_from(twoj as usize + mdashi - mi - 2 * t).unwrap_or_else(|_| {
                panic!(
                    "Unable to convert `{}` to `i32`.",
                    twoj as usize + mdashi - mi - 2 * t
                )
            }),
        ) * (beta / 2.0).sin().powi(
            i32::try_from(2 * t + mi - mdashi).unwrap_or_else(|_| {
                panic!("Unable to convert `{}` to `i32`.", 2 * t + mi - mdashi)
            }),
        );

        if t % 2 == 0 {
            acc + (num / den) * trigfactor
        } else {
            acc - (num / den) * trigfactor
        }
    });

    prefactor * d
}

/// Returns the Wigner rotation matrix in the Euler-angle parametrisation for any integral or
/// half-integral $`j`$ whose elements are defined by
///
/// ```math
/// \hat{R}(\alpha, \beta, \gamma) \ket{jm}
/// = \sum_{m'} \ket{jm'} D^{(j)}_{m'm}(\alpha, \beta, \gamma).
/// ```
///
/// and given in [`dmat_euler_gen_element`].
///
/// # Arguments
///
/// * `twoj` - Two times the angular momentum $`2j`$. If this is even, $`j`$ is integral; otherwise,
/// $`j`$ is half-integral.
/// * `euler_angles` - A triplet of Euler angles $`(\alpha, \beta, \gamma)`$ in radians, following
/// the Whitaker convention, *i.e.* $`z_2-y-z_1`$ (extrinsic rotations).
/// * `increasingm` - If `true`, the rows and columns of $`\mathbf{D}^{(j)}`$ are
/// arranged in increasing order of $`m_l = -l, \ldots, l`$. If `false`, the order is reversed:
/// $`m_l = l, \ldots, -l`$. The recommended default is `false`, in accordance with convention.
///
/// # Returns
///
/// The matrix $`\mathbf{D}^{(j)}(\alpha, \beta, \gamma)`$.
#[must_use]
pub fn dmat_euler_gen(
    twoj: u32,
    euler_angles: (f64, f64, f64),
    increasingm: bool,
) -> Array2<Complex<f64>> {
    let dim = twoj as usize + 1;
    let mut dmat = Array2::<Complex<f64>>::zeros((dim, dim));
    for mdashi in 0..dim {
        for mi in 0..dim {
            dmat[(mdashi, mi)] = dmat_euler_gen_element(twoj, mdashi, mi, euler_angles);
        }
    }
    if !increasingm {
        dmat.invert_axis(Axis(0));
        dmat.invert_axis(Axis(1));
    }
    dmat
}

/// Returns the Wigner rotation matrix in the angle-axis parametrisation for any integral or
/// half-integral $`j`$  whose elements are defined by
///
/// ```math
/// \hat{R}(\phi\hat{\mathbf{n}}) \ket{jm}
/// = \sum_{m'} \ket{jm'} D^{(j)}_{m'm}(\phi\hat{\mathbf{n}}).
/// ```
///
/// # Arguments
///
/// * `twoj` - Two times the angular momentum $`2j`$. If this is even, $`j`$ is integral; otherwise,
/// $`j`$ is half-integral.
/// * `angle` - The angle $`\phi`$ of the rotation in radians. A positive rotation is an
/// anticlockwise rotation when looking down `axis`.
/// * `axis` - A space-fixed vector defining the axis of rotation. The supplied vector will be
/// normalised.
/// * `increasingm` - If `true`, the rows and columns of $`\mathbf{D}^{(1/2)}`$ are
/// arranged in increasing order of $`m_l = -l, \ldots, l`$. If `false`, the order is reversed:
/// $`m_l = l, \ldots, -l`$. The recommended default is `false`, in accordance with convention.
///
/// # Returns
///
/// The matrix $`\mathbf{D}^{(j)}(\phi\hat{\mathbf{n}})`$.
#[must_use]
pub fn dmat_angleaxis_gen(
    twoj: u32,
    angle: f64,
    axis: Vector3<f64>,
    increasingm: bool,
) -> Array2<Complex<f64>> {
    let euler_angles = angleaxis_to_euler(angle, axis);
    dmat_euler_gen(twoj, euler_angles, increasingm)
}

/// Converts an angle and axis of rotation to Euler angles using the equations in Section
/// (**3**-5.4) in Altmann, S. L. Rotations, Quaternions, and Double Groups. (Dover
/// Publications, Inc., 2005), but with an extended range,
///
/// ```math
/// 0 \le \alpha \le 2\pi, \quad
/// 0 \le \beta \le \pi, \quad
/// 0 \le \gamma \le 4\pi,
/// ```
///
/// such that all angle-axis parametrisations of $`\phi\hat{\mathbf{n}}`$ for
/// $`0 \le \phi \le 4 \pi`$ are mapped to unique triplets of $`(\alpha, \beta, \gamma)`$,
/// as explained in Fan, P.-D., Chen, J.-Q., Mcaven, L. & Butler, P. Unique Euler angles and
/// self-consistent multiplication tables for double point groups. *International Journal of
/// Quantum Chemistry* **75**, 1–9 (1999),
/// [DOI](https://doi.org/10.1002/(SICI)1097-461X(1999)75:1<1::AID-QUA1>3.0.CO;2-V).
///
/// When $`\beta = 0`$, only the sum $`\alpha+\gamma`$ is determined. Likewise, when
/// $`\beta = \pi`$, only the difference $`\alpha-\gamma`$ is determined. We thus set
/// $`\alpha = 0`$ in these cases and solve for $`\gamma`$ without changing the nature of the
/// results.
///
/// # Arguments
///
/// * `angle` - The angle $`\phi`$ of the rotation in radians. A positive rotation is an
/// anticlockwise rotation when looking down `axis`.
/// * `axis` - A space-fixed vector defining the axis of rotation $`\hat{\mathbf{n}}`$. The supplied
/// vector will be normalised.
///
/// # Returns
///
/// The tuple containing the Euler angles $`(\alpha, \beta, \gamma)`$ in radians, following the
/// Whitaker convention.
fn angleaxis_to_euler(angle: f64, axis: Vector3<f64>) -> (f64, f64, f64) {
    let normalised_axis = axis.normalize();
    let nx = normalised_axis.x;
    let ny = normalised_axis.y;
    let nz = normalised_axis.z;

    let double_angle = angle.rem_euclid(4.0 * std::f64::consts::PI);
    let basic_angle = angle.rem_euclid(2.0 * std::f64::consts::PI);
    let double = approx::relative_eq!(
        angle.div_euclid(2.0 * std::f64::consts::PI).rem_euclid(2.0),
        1.0,
        epsilon = 1e-14,
        max_relative = 1e-14
    );

    let cosbeta = 1.0 - 2.0 * (nx.powi(2) + ny.powi(2)) * (basic_angle / 2.0).sin().powi(2);
    let cosbeta = if cosbeta.abs() > 1.0 {
        // Numerical errors can cause cosbeta to be outside [-1, 1].
        approx::assert_relative_eq!(cosbeta.abs(), 1.0, epsilon = 1e-14, max_relative = 1e-14);
        cosbeta.round()
    } else {
        cosbeta
    };

    // acos gives 0 <= beta <= pi.
    let beta = cosbeta.acos();

    let (alpha, gamma) =
        if approx::relative_ne!(cosbeta.abs(), 1.0, epsilon = 1e-14, max_relative = 1e-14) {
            // cosbeta != 1 or -1, beta != 0 or pi
            // alpha and gamma are given by Equations (**3**-5.4) to (**3**-5.10)
            // in Altmann, S. L. Rotations, Quaternions, and Double Groups. (Dover Publications,
            // Inc., 2005).
            // These equations yield the same alpha and gamma for phi and phi+2pi.
            // We therefore account for double-group behaviours separately.
            let num_alpha =
                -nx * basic_angle.sin() + 2.0 * ny * nz * (basic_angle / 2.0).sin().powi(2);
            let den_alpha =
                ny * basic_angle.sin() + 2.0 * nx * nz * (basic_angle / 2.0).sin().powi(2);
            let alpha = num_alpha
                .atan2(den_alpha)
                .rem_euclid(2.0 * std::f64::consts::PI);

            let num_gamma =
                nx * basic_angle.sin() + 2.0 * ny * nz * (basic_angle / 2.0).sin().powi(2);
            let den_gamma =
                ny * basic_angle.sin() - 2.0 * nx * nz * (basic_angle / 2.0).sin().powi(2);
            let gamma_raw = num_gamma.atan2(den_gamma);
            let gamma = if double {
                (gamma_raw + 2.0 * std::f64::consts::PI).rem_euclid(4.0 * std::f64::consts::PI)
            } else {
                gamma_raw.rem_euclid(4.0 * std::f64::consts::PI)
            };

            (alpha, gamma)
        } else if approx::relative_eq!(cosbeta, 1.0, epsilon = 1e-14, max_relative = 1e-14) {
            // cosbeta == 1, beta == 0
            // cos(0.5(alpha+gamma)) = cos(0.5phi)
            // We set alpha == 0 by convention.
            // We then set gamma = phi mod (4*pi).
            (0.0, double_angle)
        } else {
            // cosbeta == -1, beta == pi
            // sin(0.5phi) must be non-zero, otherwise cosbeta == 1, a
            // contradiction.
            // sin(0.5(alpha-gamma)) = -nx*sin(0.5phi)
            // cos(0.5(alpha-gamma)) = +ny*sin(0.5phi)
            // We set alpha == 0 by convention.
            // gamma then lies in [-2pi, 2pi].
            // We obtain the same gamma for phi and phi+2pi.
            // We therefore account for double-group behaviours separately.
            let gamma_raw = 2.0 * nx.atan2(ny);
            let gamma = if double {
                (gamma_raw + 2.0 * std::f64::consts::PI).rem_euclid(4.0 * std::f64::consts::PI)
            } else {
                gamma_raw.rem_euclid(4.0 * std::f64::consts::PI)
            };

            (0.0, gamma)
        };

    (alpha, beta, gamma)
}