Skip to main content

qsym2/target/determinant/
determinant_analysis.rs

1//! Implementation of symmetry analysis for Slater determinants.
2
3use std::fmt;
4use std::ops::Mul;
5
6use anyhow::{self, Context, ensure, format_err};
7use approx;
8use derive_builder::Builder;
9use itertools::{Itertools, izip};
10use log;
11use ndarray::{Array1, Array2, Axis, Ix2};
12use ndarray_linalg::{
13    UPLO,
14    eig::Eig,
15    eigh::Eigh,
16    solve::Determinant,
17    types::{Lapack, Scalar},
18};
19use num_complex::{Complex, ComplexFloat};
20use num_traits::{Float, ToPrimitive, Zero};
21
22use crate::analysis::{
23    EigenvalueComparisonMode, Orbit, OrbitIterator, Overlap, RepAnalysis, fn_calc_xmat_complex,
24    fn_calc_xmat_real,
25};
26use crate::angmom::spinor_rotation_3d::StructureConstraint;
27use crate::auxiliary::misc::complex_modified_gram_schmidt;
28use crate::chartab::chartab_group::CharacterProperties;
29use crate::chartab::{DecompositionError, SubspaceDecomposable};
30use crate::group::GroupType;
31use crate::io::format::{QSym2Output, log_subtitle, qsym2_output};
32use crate::symmetry::symmetry_element::symmetry_operation::SpecialSymmetryTransformation;
33use crate::symmetry::symmetry_group::SymmetryGroupProperties;
34use crate::symmetry::symmetry_transformation::{SymmetryTransformable, SymmetryTransformationKind};
35use crate::target::determinant::SlaterDeterminant;
36
37// =======
38// Overlap
39// =======
40
41impl<'a, T, SC> Overlap<T, Ix2> for SlaterDeterminant<'a, T, SC>
42where
43    T: Lapack
44        + ComplexFloat<Real = <T as Scalar>::Real>
45        + fmt::Debug
46        + Mul<<T as ComplexFloat>::Real, Output = T>,
47    <T as ComplexFloat>::Real: fmt::Debug
48        + approx::RelativeEq<<T as ComplexFloat>::Real>
49        + approx::AbsDiffEq<Epsilon = <T as Scalar>::Real>,
50    SC: StructureConstraint + Eq + fmt::Display,
51{
52    fn complex_symmetric(&self) -> bool {
53        self.complex_symmetric
54    }
55
56    /// Computes the overlap between two Slater determinants.
57    ///
58    /// Determinants with fractional electrons are currently not supported.
59    ///
60    /// When one or both of the Slater determinants have been acted on by an antiunitary operation,
61    /// the correct Hermitian or complex-symmetric metric will be chosen in the evalulation of the
62    /// overlap.
63    ///
64    /// # Arguments
65    ///
66    /// * `metric` - The atomic-orbital overlap matrix with respect to the conventional sesquilinear
67    ///   inner product.
68    /// * `metric_h` - The atomic-orbital overlap matrix with respect to the bilinear inner product.
69    ///
70    /// # Panics
71    ///
72    /// Panics if `self` and `other` have mismatched spin constraints or numbers of coefficient
73    /// matrices, or if fractional occupation numbers are detected.
74    fn overlap(
75        &self,
76        other: &Self,
77        metric: Option<&Array2<T>>,
78        metric_h: Option<&Array2<T>>,
79    ) -> Result<T, anyhow::Error> {
80        ensure!(
81            self.structure_constraint == other.structure_constraint,
82            "Inconsistent structure constraints between `self` and `other`."
83        );
84        ensure!(
85            self.coefficients.len() == other.coefficients.len(),
86            "Inconsistent numbers of coefficient matrices between `self` and `other`."
87        );
88        ensure!(
89            self.baos == other.baos,
90            "Inconsistent basis angular order between `self` and `other`."
91        );
92        ensure!(
93            self.complex_symmetric == other.complex_symmetric,
94            "Inconsistent `complex_symmetric` between `self` and `other`."
95        );
96
97        let thresh = Float::sqrt(self.threshold * other.threshold);
98        ensure!(
99            self.occupations
100                .iter()
101                .chain(other.occupations.iter())
102                .all(|occs| occs.iter().all(|&occ| approx::relative_eq!(
103                    occ,
104                    occ.round(),
105                    epsilon = thresh,
106                    max_relative = thresh
107                ))),
108            "Overlaps between determinants with fractional occupation numbers are currently not supported."
109        );
110
111        let sao = metric.ok_or_else(|| format_err!("No atomic-orbital metric found."))?;
112        let sao_h = metric_h.unwrap_or(sao);
113
114        let ov = izip!(
115            &self.coefficients,
116            &self.occupations,
117            &other.coefficients,
118            &other.occupations
119        )
120        .map(|(cw, occw, cx, occx)| {
121            let nonzero_occ_w = occw.iter().positions(|&occ| occ > thresh).collect_vec();
122            let cw_o = cw.select(Axis(1), &nonzero_occ_w);
123            let nonzero_occ_x = occx.iter().positions(|&occ| occ > thresh).collect_vec();
124            let cx_o = cx.select(Axis(1), &nonzero_occ_x);
125
126            let mo_ov_mat = if self.complex_symmetric() {
127                match (self.complex_conjugated, other.complex_conjugated) {
128                    (false, false) => cw_o.t().dot(sao_h).dot(&cx_o),
129                    (true, false) => cw_o.t().dot(sao).dot(&cx_o),
130                    (false, true) => cx_o.t().dot(sao).dot(&cw_o),
131                    (true, true) => cw_o.t().dot(&sao_h.t()).dot(&cx_o),
132                }
133            } else {
134                match (self.complex_conjugated, other.complex_conjugated) {
135                    (false, false) => cw_o.t().mapv(|x| x.conj()).dot(sao).dot(&cx_o),
136                    (true, false) => cw_o.t().mapv(|x| x.conj()).dot(sao_h).dot(&cx_o),
137                    (false, true) => cx_o
138                        .t()
139                        .mapv(|x| x.conj())
140                        .dot(sao_h)
141                        .dot(&cw_o)
142                        .mapv(|x| x.conj()),
143                    (true, true) => cw_o.t().mapv(|x| x.conj()).dot(&sao.t()).dot(&cx_o),
144                }
145            };
146            mo_ov_mat
147                .det()
148                .expect("The determinant of the MO overlap matrix could not be found.")
149        })
150        .fold(T::one(), |acc, x| acc * x);
151
152        let implicit_factor = self.structure_constraint.implicit_factor()?;
153        if implicit_factor > 1 {
154            let p_i32 = i32::try_from(implicit_factor)?;
155            Ok(ComplexFloat::powi(ov, p_i32))
156        } else {
157            Ok(ov)
158        }
159    }
160
161    /// Returns the mathematical definition of the overlap between two Slater determinants.
162    fn overlap_definition(&self) -> String {
163        let k = if self.complex_symmetric() { "κ " } else { "" };
164        format!("⟨{k}Ψ_1|Ψ_2⟩ = ∫ [{k}Ψ_1(x^Ne)]* Ψ_2(x^Ne) dx^Ne")
165    }
166}
167
168// ==============================
169// SlaterDeterminantSymmetryOrbit
170// ==============================
171
172// -----------------
173// Struct definition
174// -----------------
175
176/// Structure to manage symmetry orbits (*i.e.* orbits generated by symmetry groups) of Slater
177/// determinants.
178#[derive(Builder, Clone)]
179pub struct SlaterDeterminantSymmetryOrbit<'a, G, T, SC>
180where
181    G: SymmetryGroupProperties,
182    T: ComplexFloat + fmt::Debug + Lapack,
183    SC: StructureConstraint + fmt::Display,
184    SlaterDeterminant<'a, T, SC>: SymmetryTransformable,
185{
186    /// The generating symmetry group.
187    group: &'a G,
188
189    /// The origin Slater determinant of the orbit.
190    origin: &'a SlaterDeterminant<'a, T, SC>,
191
192    /// The threshold for determining zero eigenvalues in the orbit overlap matrix.
193    linear_independence_threshold: <T as ComplexFloat>::Real,
194
195    /// The threshold for determining if calculated multiplicities in representation analysis are
196    /// integral.
197    integrality_threshold: <T as ComplexFloat>::Real,
198
199    /// The kind of transformation determining the way the symmetry operations in `group` act on
200    /// [`Self::origin`].
201    symmetry_transformation_kind: SymmetryTransformationKind,
202
203    /// The overlap matrix between the symmetry-equivalent Slater determinants in the orbit.
204    #[builder(setter(skip), default = "None")]
205    smat: Option<Array2<T>>,
206
207    /// The eigenvalues of the overlap matrix between the symmetry-equivalent Slater determinants in
208    /// the orbit.
209    #[builder(setter(skip), default = "None")]
210    pub(crate) smat_eigvals: Option<Array1<T>>,
211
212    /// The $`\mathbf{X}`$ matrix for the overlap matrix between the symmetry-equivalent Slater
213    /// determinants in the orbit.
214    ///
215    /// See [`RepAnalysis::xmat`] for further information.
216    #[builder(setter(skip), default = "None")]
217    xmat: Option<Array2<T>>,
218
219    /// An enumerated type specifying the comparison mode for filtering out orbit overlap
220    /// eigenvalues.
221    eigenvalue_comparison_mode: EigenvalueComparisonMode,
222}
223
224// ----------------------------
225// Struct method implementation
226// ----------------------------
227
228impl<'a, G, T, SC> SlaterDeterminantSymmetryOrbit<'a, G, T, SC>
229where
230    G: SymmetryGroupProperties + Clone,
231    T: ComplexFloat + fmt::Debug + Lapack,
232    SC: StructureConstraint + Clone + fmt::Display,
233    SlaterDeterminant<'a, T, SC>: SymmetryTransformable,
234{
235    /// Returns a builder for constructing a new Slater determinant symmetry orbit.
236    pub fn builder() -> SlaterDeterminantSymmetryOrbitBuilder<'a, G, T, SC> {
237        SlaterDeterminantSymmetryOrbitBuilder::default()
238    }
239}
240
241impl<'a, G, T, SC> SlaterDeterminantSymmetryOrbit<'a, G, T, SC>
242where
243    G: SymmetryGroupProperties,
244    T: ComplexFloat + fmt::Debug + Lapack,
245    SC: StructureConstraint + fmt::Display,
246    SlaterDeterminant<'a, T, SC>: SymmetryTransformable,
247{
248    #[allow(clippy::type_complexity)]
249    pub fn action(
250        &self,
251    ) -> fn(
252        &G::GroupElement,
253        &SlaterDeterminant<'a, T, SC>,
254    ) -> Result<SlaterDeterminant<'a, T, SC>, anyhow::Error> {
255        match self.symmetry_transformation_kind {
256            SymmetryTransformationKind::Spatial => |op, det| {
257                det.sym_transform_spatial(op).with_context(|| {
258                    format!("Unable to apply `{op}` spatially on the origin determinant")
259                })
260            },
261            SymmetryTransformationKind::SpatialWithSpinTimeReversal => |op, det| {
262                det.sym_transform_spatial_with_spintimerev(op).with_context(|| {
263                    format!("Unable to apply `{op}` spatially (with spin-including time reversal) on the origin determinant")
264                })
265            },
266            SymmetryTransformationKind::Spin => |op, det| {
267                det.sym_transform_spin(op).with_context(|| {
268                    format!("Unable to apply `{op}` spin-wise on the origin determinant")
269                })
270            },
271            SymmetryTransformationKind::SpinSpatial => |op, det| {
272                det.sym_transform_spin_spatial(op).with_context(|| {
273                    format!("Unable to apply `{op}` spin-spatially on the origin determinant")
274                })
275            },
276        }
277    }
278}
279
280impl<'a, G, SC> SlaterDeterminantSymmetryOrbit<'a, G, f64, SC>
281where
282    G: SymmetryGroupProperties,
283    SC: StructureConstraint + fmt::Display,
284    SlaterDeterminant<'a, f64, SC>: SymmetryTransformable,
285{
286    fn_calc_xmat_real!(
287        /// Calculates the $`\mathbf{X}`$ matrix for real and symmetric overlap matrix
288        /// $`\mathbf{S}`$ between the symmetry-equivalent Slater determinants in the orbit.
289        ///
290        /// The resulting $`\mathbf{X}`$ is stored in the orbit.
291        ///
292        /// # Arguments
293        ///
294        /// * `preserves_full_rank` - If `true`, when $`\mathbf{S}`$ is already of full rank, then
295        /// $`\mathbf{X}`$ is set to be the identity matrix to avoid mixing the orbit determinants.
296        /// If `false`, $`\mathbf{X}`$ also orthogonalises $`\mathbf{S}`$ even when it is already of
297        /// full rank.
298        pub calc_xmat
299    );
300}
301
302impl<'a, G, T, SC> SlaterDeterminantSymmetryOrbit<'a, G, Complex<T>, SC>
303where
304    G: SymmetryGroupProperties,
305    T: Float + Scalar<Complex = Complex<T>>,
306    Complex<T>: ComplexFloat<Real = T> + Scalar<Real = T, Complex = Complex<T>> + Lapack,
307    SC: StructureConstraint + fmt::Display,
308    SlaterDeterminant<'a, Complex<T>, SC>: SymmetryTransformable + Overlap<Complex<T>, Ix2>,
309{
310    fn_calc_xmat_complex!(
311        /// Calculates the $`\mathbf{X}`$ matrix for complex and symmetric or Hermitian overlap
312        /// matrix $`\mathbf{S}`$ between the symmetry-equivalent Slater determinants in the orbit.
313        ///
314        /// The resulting $`\mathbf{X}`$ is stored in the orbit.
315        ///
316        /// # Arguments
317        ///
318        /// * `preserves_full_rank` - If `true`, when $`\mathbf{S}`$ is already of full rank, then
319        /// $`\mathbf{X}`$ is set to be the identity matrix to avoid mixing the orbit determinants.
320        /// If `false`, $`\mathbf{X}`$ also orthogonalises $`\mathbf{S}`$ even when it is already of
321        /// full rank.
322        pub calc_xmat
323    );
324}
325
326// ---------------------
327// Trait implementations
328// ---------------------
329
330// ~~~~~
331// Orbit
332// ~~~~~
333
334impl<'a, G, T, SC> Orbit<G, SlaterDeterminant<'a, T, SC>>
335    for SlaterDeterminantSymmetryOrbit<'a, G, T, SC>
336where
337    G: SymmetryGroupProperties,
338    T: ComplexFloat + fmt::Debug + Lapack,
339    SC: StructureConstraint + fmt::Display,
340    SlaterDeterminant<'a, T, SC>: SymmetryTransformable,
341{
342    type OrbitIter = OrbitIterator<'a, G, SlaterDeterminant<'a, T, SC>>;
343
344    fn group(&self) -> &G {
345        self.group
346    }
347
348    fn origin(&self) -> &SlaterDeterminant<'a, T, SC> {
349        self.origin
350    }
351
352    fn iter(&self) -> Self::OrbitIter {
353        OrbitIterator::new(
354            self.group,
355            self.origin,
356            self.action(),
357            // match self.symmetry_transformation_kind {
358            //     SymmetryTransformationKind::Spatial => |op, det| {
359            //         det.sym_transform_spatial(op).with_context(|| {
360            //             format!("Unable to apply `{op}` spatially on the origin determinant")
361            //         })
362            //     },
363            //     SymmetryTransformationKind::SpatialWithSpinTimeReversal => |op, det| {
364            //         det.sym_transform_spatial_with_spintimerev(op).with_context(|| {
365            //             format!("Unable to apply `{op}` spatially (with spin-including time reversal) on the origin determinant")
366            //         })
367            //     },
368            //     SymmetryTransformationKind::Spin => |op, det| {
369            //         det.sym_transform_spin(op).with_context(|| {
370            //             format!("Unable to apply `{op}` spin-wise on the origin determinant")
371            //         })
372            //     },
373            //     SymmetryTransformationKind::SpinSpatial => |op, det| {
374            //         det.sym_transform_spin_spatial(op).with_context(|| {
375            //             format!("Unable to apply `{op}` spin-spatially on the origin determinant")
376            //         })
377            //     },
378            // },
379        )
380    }
381}
382
383// ~~~~~~~~~~~
384// RepAnalysis
385// ~~~~~~~~~~~
386
387impl<'a, G, T, SC> RepAnalysis<G, SlaterDeterminant<'a, T, SC>, T, Ix2>
388    for SlaterDeterminantSymmetryOrbit<'a, G, T, SC>
389where
390    G: SymmetryGroupProperties,
391    G::CharTab: SubspaceDecomposable<T>,
392    T: Lapack
393        + ComplexFloat<Real = <T as Scalar>::Real>
394        + fmt::Debug
395        + Mul<<T as ComplexFloat>::Real, Output = T>,
396    <T as ComplexFloat>::Real: fmt::Debug
397        + Zero
398        + From<u16>
399        + ToPrimitive
400        + approx::RelativeEq<<T as ComplexFloat>::Real>
401        + approx::AbsDiffEq<Epsilon = <T as Scalar>::Real>,
402    SC: StructureConstraint + Eq + fmt::Display,
403    SlaterDeterminant<'a, T, SC>: SymmetryTransformable,
404{
405    fn set_smat(&mut self, smat: Array2<T>) {
406        self.smat = Some(smat)
407    }
408
409    fn smat(&self) -> Option<&Array2<T>> {
410        self.smat.as_ref()
411    }
412
413    fn xmat(&self) -> &Array2<T> {
414        self.xmat
415            .as_ref()
416            .expect("Orbit overlap orthogonalisation matrix not found.")
417    }
418
419    fn norm_preserving_scalar_map(&self, i: usize) -> Result<fn(T) -> T, anyhow::Error> {
420        if self.origin.complex_symmetric {
421            Err(format_err!(
422                "`norm_preserving_scalar_map` is currently not implemented for complex-symmetric overlaps. This thus precludes the use of the Cayley table to speed up the computation of the orbit overlap matrix."
423            ))
424        } else if self
425            .group
426            .get_index(i)
427            .unwrap_or_else(|| panic!("Group operation index `{i}` not found."))
428            .contains_time_reversal()
429        {
430            Ok(ComplexFloat::conj)
431        } else {
432            Ok(|x| x)
433        }
434    }
435
436    fn integrality_threshold(&self) -> <T as ComplexFloat>::Real {
437        self.integrality_threshold
438    }
439
440    fn eigenvalue_comparison_mode(&self) -> &EigenvalueComparisonMode {
441        &self.eigenvalue_comparison_mode
442    }
443
444    /// Reduces the representation or corepresentation spanned by the determinants in the orbit to
445    /// a direct sum of the irreducible representations or corepresentations of the generating
446    /// symmetry group.
447    ///
448    /// # Returns
449    ///
450    /// The decomposed result.
451    ///
452    /// # Errors
453    ///
454    /// Errors if the decomposition fails, *e.g.* because one or more calculated multiplicities
455    /// are non-integral, or also because the combination of group type, transformation type, and
456    /// oddity of the number of electrons would not give sensible symmetry results. In particular,
457    /// spin or spin-spatial symmetry analysis of odd-electron systems in unitary-represented
458    /// magnetic groups is not valid.
459    fn analyse_rep(
460        &self,
461    ) -> Result<
462        <<G as CharacterProperties>::CharTab as SubspaceDecomposable<T>>::Decomposition,
463        DecompositionError,
464    > {
465        log::debug!("Analysing representation symmetry for a Slater determinant...");
466        let nelectrons_float = self.origin().nelectrons();
467        if approx::relative_eq!(
468            nelectrons_float.round(),
469            nelectrons_float,
470            epsilon = self.integrality_threshold,
471            max_relative = self.integrality_threshold
472        ) {
473            let nelectrons_usize = nelectrons_float.round().to_usize().unwrap_or_else(|| {
474                panic!(
475                    "Unable to convert the number of electrons `{nelectrons_float:.7}` to `usize`."
476                );
477            });
478            let (valid_symmetry, err_str) = if nelectrons_usize.rem_euclid(2) == 0 {
479                // Even number of electrons; always valid
480                (true, String::new())
481            } else {
482                // Odd number of electrons; validity depends on group and orbit type
483                match self.symmetry_transformation_kind {
484                    SymmetryTransformationKind::Spatial => (true, String::new()),
485                    SymmetryTransformationKind::SpatialWithSpinTimeReversal
486                        | SymmetryTransformationKind::Spin
487                        | SymmetryTransformationKind::SpinSpatial => {
488                        match self.group().group_type() {
489                            GroupType::Ordinary(_) => (true, String::new()),
490                            GroupType::MagneticGrey(_) | GroupType::MagneticBlackWhite(_) => {
491                                (!self.group().unitary_represented(),
492                                "Unitary-represented magnetic groups cannot be used for symmetry analysis of odd-electron systems where spin is treated explicitly.".to_string())
493                            }
494                        }
495                    }
496                }
497            };
498
499            if valid_symmetry {
500                let chis = self
501                    .calc_characters()
502                    .map_err(|err| DecompositionError(err.to_string()))?;
503                log::debug!("Characters calculated.");
504
505                log_subtitle("Determinant orbit characters");
506                qsym2_output!("");
507                self.characters_to_string(&chis, self.integrality_threshold)
508                    .log_output_display();
509                qsym2_output!("");
510
511                let res = self.group().character_table().reduce_characters(
512                    &chis.iter().map(|(cc, chi)| (cc, *chi)).collect::<Vec<_>>(),
513                    self.integrality_threshold(),
514                );
515                log::debug!("Characters reduced.");
516                log::debug!("Analysing representation symmetry for a Slater determinant... Done.");
517                res
518            } else {
519                Err(DecompositionError(err_str))
520            }
521        } else {
522            Err(DecompositionError(format!(
523                "Symmetry analysis for determinant with non-integer number of electrons `{nelectrons_float:.7}` (threshold = {:.3e}) not supported.",
524                self.integrality_threshold
525            )))
526        }
527    }
528}