1use 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
37impl<'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 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 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#[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 group: &'a G,
188
189 origin: &'a SlaterDeterminant<'a, T, SC>,
191
192 linear_independence_threshold: <T as ComplexFloat>::Real,
194
195 integrality_threshold: <T as ComplexFloat>::Real,
198
199 symmetry_transformation_kind: SymmetryTransformationKind,
202
203 #[builder(setter(skip), default = "None")]
205 smat: Option<Array2<T>>,
206
207 #[builder(setter(skip), default = "None")]
210 pub(crate) smat_eigvals: Option<Array1<T>>,
211
212 #[builder(setter(skip), default = "None")]
217 xmat: Option<Array2<T>>,
218
219 eigenvalue_comparison_mode: EigenvalueComparisonMode,
222}
223
224impl<'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 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 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 pub calc_xmat
323 );
324}
325
326impl<'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 )
380 }
381}
382
383impl<'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 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 (true, String::new())
481 } else {
482 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}