use std::fmt;
use std::ops::Mul;
use anyhow::{self, ensure, format_err, Context};
use approx;
use derive_builder::Builder;
use itertools::Itertools;
use log;
use nalgebra::Point3;
use ndarray::{Array1, Array2, Axis, Ix1};
use ndarray_linalg::{
eig::Eig,
eigh::Eigh,
types::{Lapack, Scalar},
UPLO,
};
use num_complex::{Complex, ComplexFloat};
use num_traits::{Float, ToPrimitive, Zero};
use rayon::prelude::*;
use crate::analysis::{
fn_calc_xmat_complex, fn_calc_xmat_real, EigenvalueComparisonMode, Orbit, OrbitIterator,
Overlap, RepAnalysis,
};
use crate::auxiliary::misc::complex_modified_gram_schmidt;
use crate::chartab::chartab_group::CharacterProperties;
use crate::chartab::{DecompositionError, SubspaceDecomposable};
use crate::io::format::{log_subtitle, qsym2_output, QSym2Output};
use crate::sandbox::target::real_space_function::RealSpaceFunction;
use crate::symmetry::symmetry_element::symmetry_operation::SpecialSymmetryTransformation;
use crate::symmetry::symmetry_group::SymmetryGroupProperties;
use crate::symmetry::symmetry_transformation::{SymmetryTransformable, SymmetryTransformationKind};
impl<T, F> Overlap<T, Ix1> for RealSpaceFunction<T, F>
where
T: ComplexFloat + Lapack + Send + Sync,
F: Clone + Sync + Send + Fn(&Point3<f64>) -> T,
{
fn complex_symmetric(&self) -> bool {
false
}
fn overlap(
&self,
other: &Self,
metric: Option<&Array1<T>>,
_: Option<&Array1<T>>,
) -> Result<T, anyhow::Error> {
let weight = metric.ok_or_else(|| {
format_err!("No weights found for `RealSpaceFunction` overlap calculation.")
})?;
ensure!(
self.grid_points.len() == other.grid_points.len(),
"Inconsistent number of grid points between `self` and `other`."
);
ensure!(
self.grid_points.len() == weight.len(),
"Inconsistent number of weight values and grid points."
);
let overlap = (0..weight.len())
.into_par_iter()
.map(|i| {
let s_pt = self.grid_points[i];
let o_pt = other.grid_points[i];
let w = weight[i];
match (self.complex_conjugated, other.complex_conjugated) {
(false, false) => self.function()(&s_pt).conj() * other.function()(&o_pt) * w,
(false, true) => {
self.function()(&s_pt).conj() * other.function()(&o_pt).conj() * w
}
(true, false) => self.function()(&s_pt) * other.function()(&o_pt) * w,
(true, true) => self.function()(&s_pt) * other.function()(&o_pt).conj() * w,
}
})
.sum();
Ok(overlap)
}
fn overlap_definition(&self) -> String {
let k = if self.complex_symmetric() { "κ " } else { "" };
format!("⟨{k}f_1|f_2⟩ = ∫ [{k}f_1(r)]* w(r) f_2(r) dr where w(r) is a required weight")
}
}
#[derive(Builder, Clone)]
pub struct RealSpaceFunctionSymmetryOrbit<'a, G, T, F>
where
G: SymmetryGroupProperties,
T: ComplexFloat + fmt::Debug + Lapack,
F: Fn(&Point3<f64>) -> T,
RealSpaceFunction<T, F>: SymmetryTransformable,
{
group: &'a G,
origin: &'a RealSpaceFunction<T, F>,
pub(crate) linear_independence_threshold: <T as ComplexFloat>::Real,
integrality_threshold: <T as ComplexFloat>::Real,
symmetry_transformation_kind: SymmetryTransformationKind,
#[builder(setter(skip), default = "None")]
smat: Option<Array2<T>>,
#[builder(setter(skip), default = "None")]
pub(crate) smat_eigvals: Option<Array1<T>>,
#[builder(setter(skip), default = "None")]
xmat: Option<Array2<T>>,
eigenvalue_comparison_mode: EigenvalueComparisonMode,
}
impl<'a, G, T, F> RealSpaceFunctionSymmetryOrbit<'a, G, T, F>
where
G: SymmetryGroupProperties + Clone,
T: ComplexFloat + fmt::Debug + Lapack,
F: Clone + Fn(&Point3<f64>) -> T,
RealSpaceFunction<T, F>: SymmetryTransformable,
{
pub fn builder() -> RealSpaceFunctionSymmetryOrbitBuilder<'a, G, T, F> {
RealSpaceFunctionSymmetryOrbitBuilder::default()
}
}
impl<'a, G, F> RealSpaceFunctionSymmetryOrbit<'a, G, f64, F>
where
G: SymmetryGroupProperties + Clone,
F: Clone + Fn(&Point3<f64>) -> f64,
{
fn_calc_xmat_real!(
pub calc_xmat
);
}
impl<'a, G, T, F> RealSpaceFunctionSymmetryOrbit<'a, G, Complex<T>, F>
where
G: SymmetryGroupProperties + Clone,
T: Float + Scalar<Complex = Complex<T>>,
Complex<T>: ComplexFloat<Real = T> + Scalar<Real = T, Complex = Complex<T>> + Lapack,
F: Clone + Fn(&Point3<f64>) -> Complex<T>,
RealSpaceFunction<Complex<T>, F>: SymmetryTransformable + Overlap<Complex<T>, Ix1>,
{
fn_calc_xmat_complex!(
pub calc_xmat
);
}
impl<'a, G, T, F> Orbit<G, RealSpaceFunction<T, F>> for RealSpaceFunctionSymmetryOrbit<'a, G, T, F>
where
G: SymmetryGroupProperties + Clone,
T: ComplexFloat + fmt::Debug + Lapack,
F: Fn(&Point3<f64>) -> T,
RealSpaceFunction<T, F>: SymmetryTransformable,
{
type OrbitIter = OrbitIterator<'a, G, RealSpaceFunction<T, F>>;
fn group(&self) -> &'a G {
self.group
}
fn origin(&self) -> &RealSpaceFunction<T, F> {
self.origin
}
fn iter(&self) -> Self::OrbitIter {
OrbitIterator::new(
self.group,
self.origin,
match self.symmetry_transformation_kind {
SymmetryTransformationKind::Spatial => |op, real_space_function| {
real_space_function.sym_transform_spatial(op).with_context(|| {
format!("Unable to apply `{op}` spatially on the origin real-space function")
})
},
SymmetryTransformationKind::SpatialWithSpinTimeReversal => {
|op, real_space_function| {
real_space_function.sym_transform_spatial_with_spintimerev(op).with_context(|| {
format!("Unable to apply `{op}` spatially (with spin-including time-reversal) on the origin real-space function")
})
}
}
SymmetryTransformationKind::Spin => {
|op, real_space_function| {
real_space_function.sym_transform_spin(op).with_context(|| {
format!("Unable to apply `{op}` spin-wise on the origin real-space function")
})
}
}
SymmetryTransformationKind::SpinSpatial => |op, real_space_function| {
real_space_function.sym_transform_spin_spatial(op).with_context(|| {
format!("Unable to apply `{op}` spin-spatially on the origin real-space function")
})
},
},
)
}
}
impl<'a, G, T, F> RepAnalysis<G, RealSpaceFunction<T, F>, T, Ix1>
for RealSpaceFunctionSymmetryOrbit<'a, G, T, F>
where
G: SymmetryGroupProperties + Clone,
G::CharTab: SubspaceDecomposable<T>,
T: Lapack
+ ComplexFloat<Real = <T as Scalar>::Real>
+ fmt::Debug
+ Send
+ Sync
+ Mul<<T as ComplexFloat>::Real, Output = T>,
<T as ComplexFloat>::Real: fmt::Debug
+ Zero
+ From<u16>
+ ToPrimitive
+ approx::RelativeEq<<T as ComplexFloat>::Real>
+ approx::AbsDiffEq<Epsilon = <T as Scalar>::Real>,
F: Clone + Sync + Send + Fn(&Point3<f64>) -> T,
RealSpaceFunction<T, F>: SymmetryTransformable,
{
fn set_smat(&mut self, smat: Array2<T>) {
self.smat = Some(smat)
}
fn smat(&self) -> Option<&Array2<T>> {
self.smat.as_ref()
}
fn xmat(&self) -> &Array2<T> {
self.xmat
.as_ref()
.expect("Orbit overlap orthogonalisation matrix not found.")
}
fn norm_preserving_scalar_map(&self, i: usize) -> Result<fn(T) -> T, anyhow::Error> {
if self.origin.complex_symmetric() {
Err(format_err!("`norm_preserving_scalar_map` is currently not implemented for complex symmetric overlaps."))
} else {
if self
.group
.get_index(i)
.unwrap_or_else(|| panic!("Group operation index `{i}` not found."))
.contains_time_reversal()
{
Ok(ComplexFloat::conj)
} else {
Ok(|x| x)
}
}
}
fn integrality_threshold(&self) -> <T as ComplexFloat>::Real {
self.integrality_threshold
}
fn eigenvalue_comparison_mode(&self) -> &EigenvalueComparisonMode {
&self.eigenvalue_comparison_mode
}
fn analyse_rep(
&self,
) -> Result<
<<G as CharacterProperties>::CharTab as SubspaceDecomposable<T>>::Decomposition,
DecompositionError,
> {
log::debug!("Analysing representation symmetry for a real-space function...");
let chis = self
.calc_characters()
.map_err(|err| DecompositionError(err.to_string()))?;
log::debug!("Characters calculated.");
log_subtitle("Real-space function orbit characters");
qsym2_output!("");
self.characters_to_string(&chis, self.integrality_threshold)
.log_output_display();
qsym2_output!("");
let res = self.group().character_table().reduce_characters(
&chis.iter().map(|(cc, chi)| (cc, *chi)).collect::<Vec<_>>(),
self.integrality_threshold(),
);
log::debug!("Characters reduced.");
log::debug!("Analysing representation symmetry for a real-space function... Done.");
res
}
}