Skip to main content

qsym2/drivers/representation_analysis/
density.rs

1//! Driver for symmetry analysis of electron densities.
2
3use std::collections::HashSet;
4use std::fmt;
5use std::ops::Mul;
6
7use anyhow::{self, bail, format_err};
8use derive_builder::Builder;
9use duplicate::duplicate_item;
10use ndarray::Array4;
11use ndarray_linalg::types::Lapack;
12use num_complex::{Complex, ComplexFloat};
13use num_traits::Float;
14use serde::{Deserialize, Serialize};
15
16use crate::analysis::{
17    EigenvalueComparisonMode, Orbit, Overlap, ProjectionDecomposition, RepAnalysis,
18};
19use crate::chartab::SubspaceDecomposable;
20use crate::chartab::chartab_group::CharacterProperties;
21use crate::drivers::QSym2Driver;
22use crate::drivers::representation_analysis::angular_function::{
23    AngularFunctionRepAnalysisParams, find_angular_function_representation,
24    find_spinor_function_representation,
25};
26use crate::drivers::representation_analysis::{
27    CharacterTableDisplay, MagneticSymmetryAnalysisKind, fn_construct_magnetic_group,
28    fn_construct_unitary_group, log_bao, log_cc_transversal,
29};
30use crate::drivers::symmetry_group_detection::SymmetryGroupDetectionResult;
31use crate::group::{GroupProperties, MagneticRepresentedGroup, UnitaryRepresentedGroup};
32use crate::io::format::{
33    QSym2Output, log_subtitle, nice_bool, qsym2_output, write_subtitle, write_title,
34};
35use crate::symmetry::symmetry_group::{
36    MagneticRepresentedSymmetryGroup, SymmetryGroupProperties, UnitaryRepresentedSymmetryGroup,
37};
38use crate::symmetry::symmetry_transformation::SymmetryTransformationKind;
39use crate::target::density::Density;
40use crate::target::density::density_analysis::DensitySymmetryOrbit;
41
42#[cfg(test)]
43#[path = "density_tests.rs"]
44mod density_tests;
45
46// ==================
47// Struct definitions
48// ==================
49
50// ----------
51// Parameters
52// ----------
53
54const fn default_true() -> bool {
55    true
56}
57const fn default_symbolic() -> Option<CharacterTableDisplay> {
58    Some(CharacterTableDisplay::Symbolic)
59}
60
61/// Structure containing control parameters for electron density representation analysis.
62#[derive(Clone, Builder, Debug, Serialize, Deserialize)]
63pub struct DensityRepAnalysisParams<T: From<f64>> {
64    /// Threshold for checking if subspace multiplicities are integral.
65    pub integrality_threshold: T,
66
67    /// Threshold for determining zero eigenvalues in the orbit overlap matrix.
68    pub linear_independence_threshold: T,
69
70    /// Threshold for checking symmetry of the orbit overlap matrix.
71    pub orbit_overlap_symmetry_threshold: f64,
72
73    /// Option indicating if the magnetic group is to be used for symmetry analysis, and if so,
74    /// whether unitary representations or unitary-antiunitary corepresentations should be used.
75    #[builder(default = "None")]
76    #[serde(default)]
77    pub use_magnetic_group: Option<MagneticSymmetryAnalysisKind>,
78
79    /// Boolean indicating if the double group is to be used for symmetry analysis.
80    #[builder(default = "false")]
81    #[serde(default)]
82    pub use_double_group: bool,
83
84    /// Boolean indicating if the Cayley table of the group, if available, should be used to speed
85    /// up the computation of orbit overlap matrices.
86    #[builder(default = "true")]
87    #[serde(default = "default_true")]
88    pub use_cayley_table: bool,
89
90    /// The kind of symmetry transformation to be applied on the reference density to generate
91    /// the orbit for symmetry analysis.
92    #[builder(default = "SymmetryTransformationKind::Spatial")]
93    #[serde(default)]
94    pub symmetry_transformation_kind: SymmetryTransformationKind,
95
96    /// Option indicating if the character table of the group used for symmetry analysis is to be
97    /// printed out.
98    #[builder(default = "Some(CharacterTableDisplay::Symbolic)")]
99    #[serde(default = "default_symbolic")]
100    pub write_character_table: Option<CharacterTableDisplay>,
101
102    /// The comparison mode for filtering out orbit overlap eigenvalues.
103    #[builder(default = "EigenvalueComparisonMode::Modulus")]
104    #[serde(default)]
105    pub eigenvalue_comparison_mode: EigenvalueComparisonMode,
106
107    /// The finite order to which any infinite-order symmetry element is reduced, so that a finite
108    /// subgroup of an infinite group can be used for the symmetry analysis.
109    #[builder(default = "None")]
110    #[serde(default)]
111    pub infinite_order_to_finite: Option<u32>,
112}
113
114impl<T> DensityRepAnalysisParams<T>
115where
116    T: Float + From<f64>,
117{
118    /// Returns a builder to construct a [`DensityRepAnalysisParams`] structure.
119    pub fn builder() -> DensityRepAnalysisParamsBuilder<T> {
120        DensityRepAnalysisParamsBuilder::default()
121    }
122}
123
124impl Default for DensityRepAnalysisParams<f64> {
125    fn default() -> Self {
126        Self::builder()
127            .integrality_threshold(1e-7)
128            .linear_independence_threshold(1e-7)
129            .orbit_overlap_symmetry_threshold(1e-7)
130            .build()
131            .expect("Unable to construct a default `DensityRepAnalysisParams<f64>`.")
132    }
133}
134
135impl<T> fmt::Display for DensityRepAnalysisParams<T>
136where
137    T: From<f64> + fmt::LowerExp + fmt::Debug,
138{
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        writeln!(
141            f,
142            "Integrality threshold: {:.3e}",
143            self.integrality_threshold
144        )?;
145        writeln!(
146            f,
147            "Linear independence threshold: {:.3e}",
148            self.linear_independence_threshold
149        )?;
150        writeln!(
151            f,
152            "Orbit-overlap symmetry threshold: {:.3e}",
153            self.orbit_overlap_symmetry_threshold
154        )?;
155        writeln!(
156            f,
157            "Orbit eigenvalue comparison mode: {}",
158            self.eigenvalue_comparison_mode
159        )?;
160        writeln!(f)?;
161        writeln!(
162            f,
163            "Use magnetic group for analysis: {}",
164            match self.use_magnetic_group {
165                None => "no",
166                Some(MagneticSymmetryAnalysisKind::Representation) =>
167                    "yes, using unitary representations",
168                Some(MagneticSymmetryAnalysisKind::Corepresentation) =>
169                    "yes, using magnetic corepresentations",
170            }
171        )?;
172        writeln!(
173            f,
174            "Use double group for analysis: {}",
175            nice_bool(self.use_double_group)
176        )?;
177        writeln!(
178            f,
179            "Use Cayley table for orbit overlap matrices: {}",
180            nice_bool(self.use_cayley_table)
181        )?;
182        if let Some(finite_order) = self.infinite_order_to_finite {
183            writeln!(f, "Infinite order to finite: {finite_order}")?;
184        }
185        writeln!(
186            f,
187            "Symmetry transformation kind: {}",
188            self.symmetry_transformation_kind
189        )?;
190        writeln!(f)?;
191        writeln!(
192            f,
193            "Write character table: {}",
194            if let Some(chartab_display) = self.write_character_table.as_ref() {
195                format!("yes, {}", chartab_display.to_string().to_lowercase())
196            } else {
197                "no".to_string()
198            }
199        )?;
200
201        Ok(())
202    }
203}
204
205// ------
206// Result
207// ------
208
209/// Structure to contain electron density representation analysis results.
210#[derive(Clone, Builder)]
211pub struct DensityRepAnalysisResult<'a, G, T>
212where
213    G: SymmetryGroupProperties + Clone,
214    G::CharTab: SubspaceDecomposable<T>,
215    T: ComplexFloat + Lapack,
216    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug,
217{
218    /// The control parameters used to obtain this set of electron density representation analysis
219    /// results.
220    parameters: &'a DensityRepAnalysisParams<<T as ComplexFloat>::Real>,
221
222    /// The densities being analysed and their associated names or descriptions.
223    densities: Vec<(String, &'a Density<'a, T>)>,
224
225    /// The group used for the representation analysis.
226    group: G,
227
228    /// The deduced symmetries of the electron densities.
229    density_symmetries: Vec<Result<<G::CharTab as SubspaceDecomposable<T>>::Decomposition, String>>,
230
231    /// The overlap eigenvalues above and below the linear independence threshold for each
232    /// electron density symmetry deduction.
233    density_symmetries_thresholds: Vec<(Option<T>, Option<T>)>,
234}
235
236impl<'a, G, T> DensityRepAnalysisResult<'a, G, T>
237where
238    G: SymmetryGroupProperties + Clone,
239    G::CharTab: SubspaceDecomposable<T>,
240    T: ComplexFloat + Lapack,
241    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug,
242{
243    /// Returns a builder to construct a new [`DensityRepAnalysisResultBuilder`]
244    /// structure.
245    pub fn builder() -> DensityRepAnalysisResultBuilder<'a, G, T> {
246        DensityRepAnalysisResultBuilder::default()
247    }
248
249    /// Returns the control parameters used to obtain this set of electron density representation
250    /// analysis results.
251    pub fn parameters(&self) -> &DensityRepAnalysisParams<<T as ComplexFloat>::Real> {
252        self.parameters
253    }
254
255    /// Returns the densities being analysed and their associated names or descriptions.
256    pub fn densities(&self) -> &Vec<(String, &'a Density<'a, T>)> {
257        &self.densities
258    }
259}
260
261impl<'a, G, T> fmt::Display for DensityRepAnalysisResult<'a, G, T>
262where
263    G: SymmetryGroupProperties + Clone,
264    G::CharTab: SubspaceDecomposable<T>,
265    T: ComplexFloat + Lapack,
266    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug + fmt::Display,
267{
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        write_subtitle(f, "Orbit-based symmetry analysis results")?;
270        writeln!(f)?;
271        writeln!(
272            f,
273            "> Group: {} ({})",
274            self.group
275                .finite_subgroup_name()
276                .map(|subgroup_name| format!("{} > {}", self.group.name(), subgroup_name))
277                .unwrap_or(self.group.name()),
278            self.group.group_type().to_string().to_lowercase()
279        )?;
280        writeln!(f)?;
281
282        let density_index_length = usize::try_from(self.densities.len().ilog10() + 1)
283            .unwrap_or(1)
284            .max(1);
285        let density_text_length = self
286            .densities
287            .iter()
288            .map(|(desc, _)| desc.chars().count())
289            .max()
290            .unwrap_or(7)
291            .max(7);
292        let symmetry_length = self
293            .density_symmetries
294            .iter()
295            .map(|den_sym_res| {
296                den_sym_res
297                    .as_ref()
298                    .map(|sym| sym.to_string())
299                    .unwrap_or_else(|err| err.clone())
300                    .chars()
301                    .count()
302            })
303            .max()
304            .unwrap_or(8)
305            .max(8);
306        let eig_above_length: usize = self
307            .density_symmetries_thresholds
308            .iter()
309            .map(|(eig_above_opt, _)| {
310                eig_above_opt
311                    .as_ref()
312                    .map(|eig_above| format!("{eig_above:+.3e}").chars().count())
313                    .unwrap_or(10)
314            })
315            .max()
316            .unwrap_or(10)
317            .max(10);
318        let eig_below_length: usize = self
319            .density_symmetries_thresholds
320            .iter()
321            .map(|(_, eig_below_opt)| {
322                eig_below_opt
323                    .as_ref()
324                    .map(|eig_below| format!("{eig_below:+.3e}").chars().count())
325                    .unwrap_or(10)
326            })
327            .max()
328            .unwrap_or(10)
329            .max(10);
330
331        let table_width = 10
332            + density_index_length
333            + density_text_length
334            + symmetry_length
335            + eig_above_length
336            + eig_below_length;
337
338        writeln!(f, "> Density results")?;
339        writeln!(f, "{}", "┈".repeat(table_width))?;
340        writeln!(
341            f,
342            " {:>density_index_length$}  {:<density_text_length$}  {:<symmetry_length$}  {:<eig_above_length$}  Eig. below",
343            "#", "Density", "Symmetry", "Eig. above",
344        )?;
345        writeln!(f, "{}", "┈".repeat(table_width))?;
346        for (deni, (((den, _), den_sym), (eig_above_opt, eig_below_opt))) in self
347            .densities
348            .iter()
349            .zip(self.density_symmetries.iter())
350            .zip(self.density_symmetries_thresholds.iter())
351            .enumerate()
352        {
353            writeln!(
354                f,
355                " {:>density_index_length$}  {:<density_text_length$}  {:<symmetry_length$}  {:<eig_above_length$}  {}",
356                deni,
357                den,
358                den_sym
359                    .as_ref()
360                    .map(|sym| sym.to_string())
361                    .unwrap_or_else(|err| err.clone()),
362                eig_above_opt
363                    .map(|eig_above| format!("{eig_above:>+.3e}"))
364                    .unwrap_or("--".to_string()),
365                eig_below_opt
366                    .map(|eig_below| format!("{eig_below:>+.3e}"))
367                    .unwrap_or("--".to_string()),
368            )?;
369        }
370        writeln!(f, "{}", "┈".repeat(table_width))?;
371        writeln!(f)?;
372
373        Ok(())
374    }
375}
376
377impl<'a, G, T> fmt::Debug for DensityRepAnalysisResult<'a, G, T>
378where
379    G: SymmetryGroupProperties + Clone,
380    G::CharTab: SubspaceDecomposable<T>,
381    T: ComplexFloat + Lapack,
382    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug + fmt::Display,
383{
384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385        writeln!(f, "{self}")
386    }
387}
388
389impl<'a, G, T> DensityRepAnalysisResult<'a, G, T>
390where
391    G: SymmetryGroupProperties + Clone,
392    G::CharTab: SubspaceDecomposable<T>,
393    T: ComplexFloat + Lapack,
394    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug + fmt::Display,
395{
396    /// Returns the symmetries of the specified densities obtained from the analysis result.
397    pub fn density_symmetries(
398        &self,
399    ) -> &Vec<Result<<G::CharTab as SubspaceDecomposable<T>>::Decomposition, String>> {
400        &self.density_symmetries
401    }
402}
403
404// ------
405// Driver
406// ------
407
408// ~~~~~~~~~~~~~~~~~
409// Struct definition
410// ~~~~~~~~~~~~~~~~~
411
412/// Driver structure for performing representation analysis on electron densities.
413#[derive(Clone, Builder)]
414#[builder(build_fn(validate = "Self::validate"))]
415pub struct DensityRepAnalysisDriver<'a, G, T>
416where
417    G: SymmetryGroupProperties + Clone,
418    G::CharTab: SubspaceDecomposable<T>,
419    T: ComplexFloat + Lapack,
420    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug,
421{
422    /// The control parameters for electron density representation analysis.
423    parameters: &'a DensityRepAnalysisParams<<T as ComplexFloat>::Real>,
424
425    /// The densities being analysed and their associated names or descriptions.
426    densities: Vec<(String, &'a Density<'a, T>)>,
427
428    /// The result from symmetry-group detection on the underlying molecular structure of the
429    /// electron densities.
430    symmetry_group: &'a SymmetryGroupDetectionResult,
431
432    /// The atomic-orbital four-centre spatial overlap matrix of the underlying basis set used to
433    /// describe the densities.
434    sao_spatial_4c: &'a Array4<T>,
435
436    /// The complex-symmetric atomic-orbital four-centre spatial overlap matrix of the underlying
437    /// basis set used to describe the densities. This is required if antiunitary symmetry
438    /// operations are involved. If none is provided, this will be assumed to be the same as
439    /// [`Self::sao_spatial_4c`].
440    #[builder(default = "None")]
441    sao_spatial_4c_h: Option<&'a Array4<T>>,
442
443    /// The control parameters for symmetry analysis of angular functions.
444    angular_function_parameters: &'a AngularFunctionRepAnalysisParams,
445
446    /// The result of the electron density representation analysis.
447    #[builder(setter(skip), default = "None")]
448    result: Option<DensityRepAnalysisResult<'a, G, T>>,
449}
450
451impl<'a, G, T> DensityRepAnalysisDriverBuilder<'a, G, T>
452where
453    G: SymmetryGroupProperties + Clone,
454    G::CharTab: SubspaceDecomposable<T>,
455    T: ComplexFloat + Lapack,
456    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug,
457{
458    fn validate(&self) -> Result<(), String> {
459        let params = self
460            .parameters
461            .ok_or("No electron density representation analysis parameters found.".to_string())?;
462
463        let sym_res = self
464            .symmetry_group
465            .ok_or("No symmetry group information found.".to_string())?;
466
467        let sao_spatial_4c = self
468            .sao_spatial_4c
469            .ok_or("No four-centre spatial SAO matrix found.".to_string())?;
470
471        if let Some(sao_spatial_4c_h) = self.sao_spatial_4c_h.flatten()
472            && sao_spatial_4c_h.shape() != sao_spatial_4c.shape()
473        {
474            return Err(
475                "Mismatched shapes between `sao_spatial_4c` and `sao_spatial_4c_h`.".to_string(),
476            );
477        }
478
479        let dens = self
480            .densities
481            .as_ref()
482            .ok_or("No electron densities found.".to_string())?;
483
484        let sym = if params.use_magnetic_group.is_some() {
485            sym_res
486                .magnetic_symmetry
487                .as_ref()
488                .ok_or("Magnetic symmetry requested for representation analysis, but no magnetic symmetry found.")?
489        } else {
490            &sym_res.unitary_symmetry
491        };
492
493        if sym.is_infinite() && params.infinite_order_to_finite.is_none() {
494            Err(format!(
495                "Representation analysis cannot be performed using the entirety of the infinite group `{}`. \
496                    Consider setting the parameter `infinite_order_to_finite` to restrict to a finite subgroup instead.",
497                sym.group_name
498                    .as_ref()
499                    .expect("No symmetry group name found.")
500            ))
501        } else {
502            let baos = dens
503                .iter()
504                .map(|(_, den)| den.bao())
505                .collect::<HashSet<_>>();
506            if baos.len() != 1 {
507                Err("Inconsistent basis angular order information between densities.".to_string())
508            } else {
509                let naos = sao_spatial_4c.shape().iter().collect::<HashSet<_>>();
510                if naos.len() != 1 {
511                    Err("The shape of the four-centre spatial SAO tensor is invalid: all four dimensions must have the same length.".to_string())
512                } else {
513                    let nao = **naos.iter().next().ok_or(
514                        "Unable to extract the dimensions of the four-centre spatial SAO tensor.",
515                    )?;
516                    if !dens.iter().all(|(_, den)| den.bao().n_funcs() == nao) {
517                        Err("The dimensions of the four-centre spatial SAO tensor do not match the number of spatial AO basis functions.".to_string())
518                    } else {
519                        Ok(())
520                    }
521                }
522            }
523        }
524    }
525}
526
527// ~~~~~~~~~~~~~~~~~~~~~~
528// Struct implementations
529// ~~~~~~~~~~~~~~~~~~~~~~
530
531// Generic for all symmetry groups G and density numeric type T
532// ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
533
534impl<'a, G, T> DensityRepAnalysisDriver<'a, G, T>
535where
536    G: SymmetryGroupProperties + Clone,
537    G::CharTab: SubspaceDecomposable<T>,
538    T: ComplexFloat + Lapack,
539    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug,
540{
541    /// Returns a builder to construct a [`DensityRepAnalysisDriver`] structure.
542    pub fn builder() -> DensityRepAnalysisDriverBuilder<'a, G, T> {
543        DensityRepAnalysisDriverBuilder::default()
544    }
545}
546
547// Specific for unitary-represented symmetry groups, but generic for density numeric type T
548// ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
549
550impl<'a, T> DensityRepAnalysisDriver<'a, UnitaryRepresentedSymmetryGroup, T>
551where
552    T: ComplexFloat + Lapack + Sync + Send,
553    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug + Sync + Send,
554    for<'b> Complex<f64>: Mul<&'b T, Output = Complex<f64>>,
555{
556    fn_construct_unitary_group!(
557        /// Constructs the unitary-represented group (which itself can be unitary or magnetic) ready
558        /// for electron density representation analysis.
559        construct_unitary_group
560    );
561}
562
563// Specific for magnetic-represented symmetry groups, but generic for density numeric type T
564// '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
565
566impl<'a, T> DensityRepAnalysisDriver<'a, MagneticRepresentedSymmetryGroup, T>
567where
568    T: ComplexFloat + Lapack + Sync + Send,
569    <T as ComplexFloat>::Real: From<f64> + Sync + Send + fmt::LowerExp + fmt::Debug,
570    for<'b> Complex<f64>: Mul<&'b T, Output = Complex<f64>>,
571{
572    fn_construct_magnetic_group!(
573        /// Constructs the magnetic-represented group (which itself can only be magnetic) ready for
574        /// electron density corepresentation analysis.
575        construct_magnetic_group
576    );
577}
578
579// Specific for unitary-represented and magnetic-represented symmetry groups and density numeric types f64 and C128
580// ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
581
582#[duplicate_item(
583    duplicate!{
584        [ dtype_nested; [f64]; [Complex<f64>] ]
585        [
586            gtype_ [ UnitaryRepresentedSymmetryGroup ]
587            dtype_ [ dtype_nested ]
588            doc_sub_ [ "Performs representation analysis using a unitary-represented group and stores the result." ]
589            analyse_fn_ [ analyse_representation ]
590            construct_group_ [ self.construct_unitary_group()? ]
591            calc_projections_ [
592                log_subtitle("Electron density projection decompositions");
593                qsym2_output!("");
594                qsym2_output!("  Density name: {den_name}");
595                qsym2_output!("");
596                qsym2_output!("  Projections are defined w.r.t. the following inner product:");
597                qsym2_output!("    {}", den_orbit.origin().overlap_definition());
598                qsym2_output!("");
599                den_orbit
600                    .projections_to_string(
601                        &den_orbit.calc_projection_compositions()?,
602                        params.integrality_threshold,
603                    )
604                    .log_output_display();
605                qsym2_output!("");
606            ]
607        ]
608    }
609    duplicate!{
610        [ dtype_nested; [f64]; [Complex<f64>] ]
611        [
612            gtype_ [ MagneticRepresentedSymmetryGroup ]
613            dtype_ [ dtype_nested ]
614            doc_sub_ [ "Performs corepresentation analysis using a magnetic-represented group and stores the result." ]
615            analyse_fn_ [ analyse_corepresentation ]
616            construct_group_ [ self.construct_magnetic_group()? ]
617            calc_projections_ [ ]
618        ]
619    }
620)]
621impl<'a> DensityRepAnalysisDriver<'a, gtype_, dtype_> {
622    #[doc = doc_sub_]
623    fn analyse_fn_(&mut self) -> Result<(), anyhow::Error> {
624        let params = self.parameters;
625        let sao_spatial_4c = self.sao_spatial_4c;
626        let sao_spatial_4c_h = self.sao_spatial_4c_h;
627        let group = construct_group_;
628        log_cc_transversal(&group);
629        let _ = find_angular_function_representation(&group, self.angular_function_parameters);
630        if group.is_double_group() {
631            let _ = find_spinor_function_representation(&group, self.angular_function_parameters);
632        }
633        let bao = self
634            .densities
635            .first()
636            .map(|(_, den)| den.bao())
637            .ok_or_else(|| {
638                format_err!("Basis angular order information could not be extracted.")
639            })?;
640        log_bao(bao, None);
641
642        let (den_symmetries, den_symmetries_thresholds): (Vec<_>, Vec<_>) =
643            self.densities.iter().map(|(den_name, den)| {
644                log::debug!("Analysing symmetry for density {den_name}...");
645                DensitySymmetryOrbit::builder()
646                    .group(&group)
647                    .origin(den)
648                    .integrality_threshold(params.integrality_threshold)
649                    .linear_independence_threshold(params.linear_independence_threshold)
650                    .orbit_overlap_symmetry_threshold(params.orbit_overlap_symmetry_threshold)
651                    .symmetry_transformation_kind(params.symmetry_transformation_kind.clone())
652                    .eigenvalue_comparison_mode(params.eigenvalue_comparison_mode.clone())
653                    .build()
654                    .map_err(|err| format_err!(err))
655                    .and_then(|mut den_orbit| {
656                        den_orbit
657                            .calc_smat(Some(sao_spatial_4c), sao_spatial_4c_h, params.use_cayley_table)?
658                            .normalise_smat()?
659                            .calc_xmat(false)?;
660                        let density_symmetry_thresholds = den_orbit
661                            .smat_eigvals
662                            .as_ref()
663                            .map(|eigvals| {
664                                let mut eigvals_vec = eigvals.iter().collect::<Vec<_>>();
665                                match den_orbit.eigenvalue_comparison_mode() {
666                                    EigenvalueComparisonMode::Modulus => {
667                                        eigvals_vec.sort_by(|a, b| {
668                                            a.abs().partial_cmp(&b.abs()).expect("Unable to compare two eigenvalues based on their moduli.")
669                                        });
670                                    }
671                                    EigenvalueComparisonMode::Real => {
672                                        eigvals_vec.sort_by(|a, b| {
673                                            a.re().partial_cmp(&b.re()).expect("Unable to compare two eigenvalues based on their real parts.")
674                                        });
675                                    }
676                                }
677                                let eigval_above = match den_orbit.eigenvalue_comparison_mode() {
678                                    EigenvalueComparisonMode::Modulus => eigvals_vec
679                                        .iter()
680                                        .find(|val| {
681                                            val.abs() >= den_orbit.linear_independence_threshold
682                                        })
683                                        .copied()
684                                        .copied(),
685                                    EigenvalueComparisonMode::Real => eigvals_vec
686                                        .iter()
687                                        .find(|val| {
688                                            val.re() >= den_orbit.linear_independence_threshold
689                                        })
690                                        .copied()
691                                        .copied(),
692                                };
693                                eigvals_vec.reverse();
694                                let eigval_below = match den_orbit.eigenvalue_comparison_mode() {
695                                    EigenvalueComparisonMode::Modulus => eigvals_vec
696                                        .iter()
697                                        .find(|val| {
698                                            val.abs() < den_orbit.linear_independence_threshold
699                                        })
700                                        .copied()
701                                        .copied(),
702                                    EigenvalueComparisonMode::Real => eigvals_vec
703                                        .iter()
704                                        .find(|val| {
705                                            val.re() < den_orbit.linear_independence_threshold
706                                        })
707                                        .copied()
708                                        .copied(),
709                                };
710                                (eigval_above, eigval_below)
711                            })
712                            .unwrap_or((None, None));
713                        let den_sym = den_orbit.analyse_rep().map_err(|err| err.to_string());
714
715                        {
716                            calc_projections_
717                        }
718
719                        Ok((den_sym, density_symmetry_thresholds))
720                    })
721                    .unwrap_or_else(|err| (Err(err.to_string()), (None, None)))
722            }).unzip();
723
724        let result = DensityRepAnalysisResult::builder()
725            .parameters(params)
726            .densities(self.densities.clone())
727            .group(group)
728            .density_symmetries(den_symmetries)
729            .density_symmetries_thresholds(den_symmetries_thresholds)
730            .build()?;
731        self.result = Some(result);
732
733        Ok(())
734    }
735}
736
737// ~~~~~~~~~~~~~~~~~~~~~
738// Trait implementations
739// ~~~~~~~~~~~~~~~~~~~~~
740
741// Generic for all symmetry groups G and density numeric type T
742// ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
743
744impl<'a, G, T> fmt::Display for DensityRepAnalysisDriver<'a, G, T>
745where
746    G: SymmetryGroupProperties + Clone,
747    G::CharTab: SubspaceDecomposable<T>,
748    T: ComplexFloat + Lapack,
749    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug,
750{
751    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
752        write_title(f, "Electron Density Symmetry Analysis")?;
753        writeln!(f)?;
754        writeln!(f, "{}", self.parameters)?;
755        Ok(())
756    }
757}
758
759impl<'a, G, T> fmt::Debug for DensityRepAnalysisDriver<'a, G, T>
760where
761    G: SymmetryGroupProperties + Clone,
762    G::CharTab: SubspaceDecomposable<T>,
763    T: ComplexFloat + Lapack,
764    <T as ComplexFloat>::Real: From<f64> + fmt::LowerExp + fmt::Debug,
765{
766    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
767        writeln!(f, "{self}")
768    }
769}
770
771// Specific for unitary/magnetic-represented groups and density numeric type f64/Complex<f64>
772// ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
773
774#[duplicate_item(
775    duplicate!{
776        [ dtype_nested; [f64]; [Complex<f64>] ]
777        [
778            gtype_ [ UnitaryRepresentedSymmetryGroup ]
779            dtype_ [ dtype_nested ]
780            analyse_fn_ [ analyse_representation ]
781        ]
782    }
783    duplicate!{
784        [ dtype_nested; [f64]; [Complex<f64>] ]
785        [
786            gtype_ [ MagneticRepresentedSymmetryGroup ]
787            dtype_ [ dtype_nested ]
788            analyse_fn_ [ analyse_corepresentation ]
789        ]
790    }
791)]
792impl<'a> QSym2Driver for DensityRepAnalysisDriver<'a, gtype_, dtype_> {
793    type Params = DensityRepAnalysisParams<f64>;
794
795    type Outcome = DensityRepAnalysisResult<'a, gtype_, dtype_>;
796
797    fn result(&self) -> Result<&Self::Outcome, anyhow::Error> {
798        self.result.as_ref().ok_or_else(|| {
799            format_err!("No electron density representation analysis results found.")
800        })
801    }
802
803    fn run(&mut self) -> Result<(), anyhow::Error> {
804        self.log_output_display();
805        self.analyse_fn_()?;
806        self.result()?.log_output_display();
807        Ok(())
808    }
809}