qsym2/target/noci/backend/matelem/
mod.rs

1use std::collections::HashSet;
2use std::fmt::{self, LowerExp};
3
4use anyhow::{self, ensure, format_err};
5use itertools::Itertools;
6use log;
7use ndarray::{Array2, Array3, ArrayView2, s};
8use ndarray_linalg::types::Lapack;
9use num_complex::ComplexFloat;
10use rayon::iter::{ParallelBridge, ParallelIterator};
11
12use crate::angmom::spinor_rotation_3d::StructureConstraint;
13use crate::symmetry::symmetry_element::SpecialSymmetryTransformation;
14use crate::symmetry::symmetry_group::SymmetryGroupProperties;
15use crate::symmetry::symmetry_transformation::SymmetryTransformable;
16use crate::target::determinant::SlaterDeterminant;
17use crate::target::noci::basis::{Basis, OrbitBasis};
18
19pub mod hamiltonian;
20pub mod overlap;
21
22pub trait OrbitMatrix<'a, T, SC>
23where
24    T: Lapack + ComplexFloat,
25    SC: StructureConstraint + Clone + fmt::Display,
26    SlaterDeterminant<'a, T, SC>: SymmetryTransformable,
27{
28    /// The type of the matrix elements.
29    type MatrixElement;
30
31    // ----------------
32    // Required methods
33    // ----------------
34    /// Calculates the matrix element between two Slater determinants.
35    ///
36    /// # Arguments
37    ///
38    /// * `det_w` - The determinant $`^{w}\Psi`$.
39    /// * `det_x` - The determinant $`^{x}\Psi`$.
40    /// * `sao` - The atomic-orbital overlap matrix.
41    /// * `thresh_offdiag` - Threshold for determining non-zero off-diagonal elements in the
42    /// orbital overlap matrix between $`^{w}\Psi`$ and $`^{x}\Psi`$ during Löwdin pairing.
43    /// * `thresh_zeroov` - Threshold for identifying zero Löwdin overlaps.
44    ///
45    /// # Returns
46    ///
47    /// The resulting matrix element.
48    fn calc_matrix_element(
49        &self,
50        det_w: &SlaterDeterminant<T, SC>,
51        det_x: &SlaterDeterminant<T, SC>,
52        sao: &ArrayView2<T>,
53        thresh_offdiag: <T as ComplexFloat>::Real,
54        thresh_zeroov: <T as ComplexFloat>::Real,
55    ) -> Result<Self::MatrixElement, anyhow::Error>;
56
57    /// Computes the transpose of a matrix element.
58    fn t(x: &Self::MatrixElement) -> Self::MatrixElement;
59
60    /// Computes the complex conjugation of a matrix element.
61    fn conj(x: &Self::MatrixElement) -> Self::MatrixElement;
62
63    /// Returns the zero matrix element.
64    fn zero(&self) -> Self::MatrixElement;
65
66    // ----------------
67    // Provided methods
68    // ----------------
69
70    /// Returns the norm-presearving scalar map connecting diagonally-symmetric elements in the
71    /// matrix.
72    fn norm_preserving_scalar_map<'b, G>(
73        &self,
74        i: usize,
75        orbit_basis: &'b OrbitBasis<'b, G, SlaterDeterminant<'a, T, SC>>,
76    ) -> Result<fn(&Self::MatrixElement) -> Self::MatrixElement, anyhow::Error>
77    where
78        G: SymmetryGroupProperties + Clone,
79        'a: 'b,
80    {
81        let group = orbit_basis.group();
82        let complex_symmetric_set = orbit_basis
83            .origins()
84            .iter()
85            .map(|det| det.complex_symmetric())
86            .collect::<HashSet<_>>();
87        ensure!(
88            complex_symmetric_set.len() == 1,
89            "Inconsistent complex-symmetric flags across origin determinants."
90        );
91        let complex_symmetric = *complex_symmetric_set
92            .iter()
93            .next()
94            .ok_or(format_err!("Unable to obtain the complex-symmetric flag."))?;
95        if complex_symmetric {
96            Err(format_err!(
97                "`norm_preserving_scalar_map` is currently not implemented for complex-symmetric inner products. This thus precludes the use of the Cayley table to speed up the computation of orbit matrices."
98            ))
99        } else {
100            if group
101                .get_index(i)
102                .unwrap_or_else(|| panic!("Group operation index `{i}` not found."))
103                .contains_time_reversal()
104            {
105                Ok(Self::conj)
106            } else {
107                Ok(Self::t)
108            }
109        }
110    }
111
112    /// Computes the entire matrix of matrix elements in an orbit basis, making use of group
113    /// closure for optimisation.
114    ///
115    /// # Arguments
116    ///
117    /// * `orbit_basis` - The orbit basis in which the matrix elements are to be computed.
118    /// * `use_cayley_table` - Boolean indicating whether group closure should be used to speed up
119    /// the computation.
120    /// * `sao` - The atomic-orbital overlap matrix.
121    /// * `thresh_offdiag` - Threshold for determining non-zero off-diagonal elements in the
122    /// orbital overlap matrix between two Slater determinants during Löwdin pairing.
123    /// * `thresh_zeroov` - Threshold for identifying zero Löwdin overlaps.
124    fn calc_orbit_matrix<'g, G>(
125        &self,
126        orbit_basis: &'g OrbitBasis<'g, G, SlaterDeterminant<'a, T, SC>>,
127        use_cayley_table: bool,
128        sao: &ArrayView2<T>,
129        thresh_offdiag: <T as ComplexFloat>::Real,
130        thresh_zeroov: <T as ComplexFloat>::Real,
131    ) -> Result<Array2<Self::MatrixElement>, anyhow::Error>
132    where
133        G: SymmetryGroupProperties + Clone,
134        T: Sync + Send,
135        <T as ComplexFloat>::Real: Sync,
136        SlaterDeterminant<'a, T, SC>: Sync,
137        Self: Sync,
138        Self::MatrixElement: Send + LowerExp,
139        'a: 'g,
140        Self::MatrixElement: Clone,
141    {
142        let group = orbit_basis.group();
143        let order = group.order();
144        let det_origins = orbit_basis.origins();
145        let n_det_origins = det_origins.len();
146        let mut mat = Array2::<Self::MatrixElement>::from_elem(
147            (n_det_origins * order, n_det_origins * order),
148            self.zero(),
149        );
150
151        if let (Some(ctb), true) = (group.cayley_table(), use_cayley_table) {
152            log::debug!(
153                "Cayley table available and its use requested. Group closure will be used to speed up orbit matrix computation."
154            );
155            // Compute unique matrix elements
156            let mut ov_elems = orbit_basis
157                .iter()
158                .collect::<Result<Vec<_>, _>>()?
159                .iter()
160                .enumerate()
161                .cartesian_product(orbit_basis.origins().iter().enumerate())
162                // .par_bridge()
163                .map(|((k_ii, k_ii_det), (jj, jj_det))| {
164                    let k = k_ii.div_euclid(n_det_origins);
165                    let ii = k_ii.rem_euclid(n_det_origins);
166                    (
167                        ii,
168                        jj,
169                        k,
170                        self.calc_matrix_element(
171                            k_ii_det,
172                            jj_det,
173                            sao,
174                            thresh_offdiag,
175                            thresh_zeroov,
176                        ),
177                    )
178                })
179                .collect::<Vec<_>>();
180            ov_elems.sort_by_key(|v| (v.0, v.1, v.2));
181            let mut ov_ii_jj_k =
182                Array3::from_elem((n_det_origins, n_det_origins, order), self.zero());
183            for (ii, jj, k, elem_res) in ov_elems {
184                log::debug!(
185                    "⟨g_{k} Ψ_{ii} | Ψ_{jj}⟩ = ⟨{} Ψ_{ii} | Ψ_{jj}⟩ = {}",
186                    group
187                        .get_index(k)
188                        .map(|g| g.to_string())
189                        .unwrap_or_else(|| format!("g_{k}")),
190                    elem_res
191                        .as_ref()
192                        .map(|v| format!("{v:+.8e}"))
193                        .unwrap_or_else(|err| err.to_string())
194                );
195                ov_ii_jj_k[(ii, jj, k)] = elem_res?;
196            }
197
198            // Populate all matrix elements
199            for v in [
200                (0..order),
201                (0..n_det_origins),
202                (0..order),
203                (0..n_det_origins),
204            ]
205            .into_iter()
206            .multi_cartesian_product()
207            {
208                let i = v[0];
209                let ii = v[1];
210                let j = v[2];
211                let jj = v[3];
212
213                let jinv = ctb
214                    .slice(s![.., j])
215                    .iter()
216                    .position(|&x| x == 0)
217                    .ok_or(format_err!(
218                        "Unable to find the inverse of group element `{j}`."
219                    ))?;
220                let k = ctb[(jinv, i)];
221                log::debug!(
222                    "{}^(-1) = {} ⇒ ⟨g_{i} Ψ_{ii} | g_{j} Ψ_{jj}⟩ = ⟨{} Ψ_{ii} | {} Ψ_{jj}⟩ = ⟨{} Ψ_{ii} | Ψ_{jj}⟩ = {:+8e}",
223                    group
224                        .get_index(j)
225                        .map(|g| g.to_string())
226                        .unwrap_or_else(|| format!("g_{j}")),
227                    group
228                        .get_index(jinv)
229                        .map(|g| g.to_string())
230                        .unwrap_or_else(|| format!("g_{jinv}")),
231                    group
232                        .get_index(i)
233                        .map(|g| g.to_string())
234                        .unwrap_or_else(|| format!("g_{i}")),
235                    group
236                        .get_index(j)
237                        .map(|g| g.to_string())
238                        .unwrap_or_else(|| format!("g_{j}")),
239                    group
240                        .get_index(k)
241                        .map(|g| g.to_string())
242                        .unwrap_or_else(|| format!("g_{k}")),
243                    ov_ii_jj_k[(ii, jj, k)],
244                );
245                mat[(i + ii * order, j + jj * order)] =
246                    self.norm_preserving_scalar_map(jinv, orbit_basis)?(&ov_ii_jj_k[(ii, jj, k)]);
247            }
248        } else {
249            log::debug!(
250                "Cayley table not available or its use not requested. Group closure will not be used for orbit matrix computation."
251            );
252            let orbit_basis_vec = orbit_basis.iter().collect::<Result<Vec<_>, _>>()?;
253            let mut elems = orbit_basis_vec
254                .iter()
255                .enumerate()
256                .cartesian_product(orbit_basis_vec.iter().enumerate())
257                .par_bridge()
258                .map(|((i_ii, i_ii_det), (j_jj, j_jj_det))| {
259                    let i = i_ii.div_euclid(n_det_origins);
260                    let ii = i_ii.rem_euclid(n_det_origins);
261                    let j = j_jj.div_euclid(n_det_origins);
262                    let jj = j_jj.rem_euclid(n_det_origins);
263                    let elem_res = self.calc_matrix_element(
264                        i_ii_det,
265                        j_jj_det,
266                        sao,
267                        thresh_offdiag,
268                        thresh_zeroov,
269                    );
270                    (i, ii, j, jj, elem_res)
271                })
272                .collect::<Vec<_>>();
273            elems.sort_by_key(|v| (v.1, v.0, v.3, v.2));
274            for (i, ii, j, jj, elem_res) in elems {
275                log::debug!(
276                    "⟨g_{i} Ψ_{ii} | g_{j} Ψ_{jj}⟩ = ⟨{} Ψ_{ii} | {} Ψ_{jj}⟩ = {}",
277                    group
278                        .get_index(i)
279                        .map(|g| g.to_string())
280                        .unwrap_or_else(|| format!("g_{i}")),
281                    group
282                        .get_index(j)
283                        .map(|g| g.to_string())
284                        .unwrap_or_else(|| format!("g_{j}")),
285                    elem_res
286                        .as_ref()
287                        .map(|v| format!("{v:+.8e}"))
288                        .unwrap_or_else(|err| err.to_string())
289                );
290                mat[(i + ii * order, j + jj * order)] = elem_res?;
291            }
292        }
293        Ok(mat)
294    }
295}