Skip to main content

qsym2/sandbox/bindings/python/representation_analysis/
real_space_function.rs

1//! Sandbox Python bindings for QSym² symmetry analysis of real-space functions.
2
3use std::path::PathBuf;
4
5use duplicate::duplicate_item;
6use nalgebra::Point3;
7use num::Complex;
8use numpy::{PyArray1, PyArray2, PyArrayMethods};
9use pyo3::exceptions::{PyIOError, PyRuntimeError};
10use pyo3::prelude::*;
11use pyo3::types::PyFunction;
12
13use crate::analysis::EigenvalueComparisonMode;
14use crate::drivers::representation_analysis::angular_function::AngularFunctionRepAnalysisParams;
15use crate::drivers::representation_analysis::{
16    CharacterTableDisplay, MagneticSymmetryAnalysisKind,
17};
18use crate::drivers::symmetry_group_detection::SymmetryGroupDetectionResult;
19use crate::drivers::QSym2Driver;
20use crate::io::format::qsym2_output;
21use crate::io::{read_qsym2_binary, QSym2FileType};
22use crate::sandbox::drivers::representation_analysis::real_space_function::{
23    RealSpaceFunctionRepAnalysisDriver, RealSpaceFunctionRepAnalysisParams,
24};
25use crate::sandbox::target::real_space_function::RealSpaceFunction;
26use crate::symmetry::symmetry_group::{
27    MagneticRepresentedSymmetryGroup, UnitaryRepresentedSymmetryGroup,
28};
29use crate::symmetry::symmetry_transformation::SymmetryTransformationKind;
30
31// =====================
32// Functions definitions
33// =====================
34
35#[duplicate_item(
36    [
37        dtype_ [ f64 ]
38        doc_sub_ [ "Python-exposed function to perform representation symmetry analysis for real-valued real-space functions and log the result via the `qsym2-output` logger at the `INFO` level." ]
39        func_sub_ [ "* `function` - A Python function callable on three Cartesian coordinates to give a scalar value. Python type: `Callable[[float, float, float], float]`." ]
40        rep_analyse_real_space_function_ [ rep_analyse_real_space_function_real ]
41    ]
42    [
43        dtype_ [ Complex<f64> ]
44        doc_sub_ [ "Python-exposed function to perform representation symmetry analysis for complex-valued real-space functions and log the result via the `qsym2-output` logger at the `INFO` level." ]
45        func_sub_ [ "* `function` - A Python function callable on three Cartesian coordinates to give a scalar value. Python type: `Callable[[float, float, float], complex]`." ]
46        rep_analyse_real_space_function_ [ rep_analyse_real_space_function_complex ]
47    ]
48)]
49#[doc = doc_sub_]
50///
51/// # Arguments
52///
53/// * `inp_sym` - A path to the [`QSym2FileType::Sym`] file containing the symmetry-group detection
54/// result for the system. This will be used to construct abstract groups and character tables for
55/// representation analysis. Python type: `str`.
56#[doc = func_sub_]
57/// * `integrality_threshold` - The threshold for verifying if subspace multiplicities are integral.
58/// Python type: `float`.
59/// * `linear_independence_threshold` - The threshold for determining the linear independence
60/// subspace via the non-zero eigenvalues of the orbit overlap matrix. Python type: `float`.
61/// * `orbit_overlap_symmetry_threshold` - The threshold for checking the symmetry of the orbit
62/// overlap matrix. Python type: `float`.
63/// * `use_magnetic_group` - An option indicating if the magnetic group is to be used for symmetry
64/// analysis, and if so, whether unitary representations or unitary-antiunitary corepresentations
65/// should be used. Python type: `None | MagneticSymmetryAnalysisKind`.
66/// * `use_double_group` - A boolean indicating if the double group of the prevailing symmetry
67/// group is to be used for representation analysis instead. Python type: `bool`.
68/// * `use_cayley_table` - A boolean indicating if the Cayley table for the group, if available,
69/// should be used to speed up the calculation of orbit overlap matrices. Python type: `bool`.
70/// * `symmetry_transformation_kind` - An enumerated type indicating the type of symmetry
71/// transformations to be performed on the origin real-space function to generate the orbit.
72/// Python type: `SymmetryTransformationKind`.
73/// * `eigenvalue_comparison_mode` - An enumerated type indicating the mode of comparison of orbit
74/// overlap eigenvalues with the specified `linear_independence_threshold`.
75/// Python type: `EigenvalueComparisonMode`.
76/// * `grid_points` - The grid points at which the real-space function is evaluated specified as a
77/// $`3 \times N`$ array where $`N`$ is the number of points. Python type: `numpy.2darray[float]`.
78/// * `weight` - The weight to be used in the computation of overlaps between real-space functions
79/// specified as a one-dimensional array. The number of weight values must match the number of grid
80/// points. Python type: `numpy.1darray[float]`.
81/// * `write_overlap_eigenvalues` - A boolean indicating if the eigenvalues of the real-space
82/// function orbit overlap matrix are to be written to the output. Python type: `bool`.
83/// * `write_character_table` - A boolean indicating if the character table of the prevailing
84/// symmetry group is to be printed out. Python type: `bool`.
85/// * `infinite_order_to_finite` - The finite order with which infinite-order generators are to be
86/// interpreted to form a finite subgroup of the prevailing infinite group. This finite subgroup
87/// will be used for symmetry analysis. Python type: `Optional[int]`.
88/// * `angular_function_integrality_threshold` - The threshold for verifying if subspace
89/// multiplicities are integral for the symmetry analysis of angular functions. Python type:
90/// `float`.
91/// * `angular_function_linear_independence_threshold` - The threshold for determining the linear
92/// independence subspace via the non-zero eigenvalues of the orbit overlap matrix for the symmetry
93/// analysis of angular functions. Python type: `float`.
94/// * `angular_function_max_angular_momentum` - The maximum angular momentum order to be used in
95/// angular function symmetry analysis. Python type: `int`.
96#[allow(clippy::too_many_arguments)]
97#[pyfunction]
98#[pyo3(signature = (
99    inp_sym,
100    function,
101    integrality_threshold,
102    linear_independence_threshold,
103    orbit_overlap_symmetry_threshold,
104    use_magnetic_group,
105    use_double_group,
106    use_cayley_table,
107    symmetry_transformation_kind,
108    eigenvalue_comparison_mode,
109    grid_points,
110    weight,
111    write_overlap_eigenvalues=true,
112    write_character_table=true,
113    infinite_order_to_finite=None,
114    angular_function_integrality_threshold=1e-7,
115    angular_function_linear_independence_threshold=1e-7,
116    angular_function_max_angular_momentum=2
117))]
118pub fn rep_analyse_real_space_function_(
119    py: Python<'_>,
120    inp_sym: PathBuf,
121    function: Py<PyFunction>,
122    integrality_threshold: f64,
123    linear_independence_threshold: f64,
124    orbit_overlap_symmetry_threshold: f64,
125    use_magnetic_group: Option<MagneticSymmetryAnalysisKind>,
126    use_double_group: bool,
127    use_cayley_table: bool,
128    symmetry_transformation_kind: SymmetryTransformationKind,
129    eigenvalue_comparison_mode: EigenvalueComparisonMode,
130    grid_points: Bound<'_, PyArray2<f64>>,
131    weight: Bound<'_, PyArray1<dtype_>>,
132    write_overlap_eigenvalues: bool,
133    write_character_table: bool,
134    infinite_order_to_finite: Option<u32>,
135    angular_function_integrality_threshold: f64,
136    angular_function_linear_independence_threshold: f64,
137    angular_function_max_angular_momentum: u32,
138) -> PyResult<()> {
139    let pd_res: SymmetryGroupDetectionResult =
140        read_qsym2_binary(inp_sym.clone(), QSym2FileType::Sym)
141            .map_err(|err| PyIOError::new_err(err.to_string()))?;
142
143    let mut file_name = inp_sym.to_path_buf();
144    file_name.set_extension(QSym2FileType::Sym.ext());
145    qsym2_output!(
146        "Symmetry-group detection results read in from {}.",
147        file_name.display(),
148    );
149    qsym2_output!("");
150
151    let afa_params = AngularFunctionRepAnalysisParams::builder()
152        .integrality_threshold(angular_function_integrality_threshold)
153        .linear_independence_threshold(angular_function_linear_independence_threshold)
154        .max_angular_momentum(angular_function_max_angular_momentum)
155        .build()
156        .map_err(|err| PyRuntimeError::new_err(err.to_string()))?;
157    let real_space_function_params = RealSpaceFunctionRepAnalysisParams::<f64>::builder()
158        .integrality_threshold(integrality_threshold)
159        .linear_independence_threshold(linear_independence_threshold)
160        .orbit_overlap_symmetry_threshold(orbit_overlap_symmetry_threshold)
161        .use_magnetic_group(use_magnetic_group.clone())
162        .use_double_group(use_double_group)
163        .use_cayley_table(use_cayley_table)
164        .symmetry_transformation_kind(symmetry_transformation_kind)
165        .eigenvalue_comparison_mode(eigenvalue_comparison_mode)
166        .write_overlap_eigenvalues(write_overlap_eigenvalues)
167        .write_character_table(if write_character_table {
168            Some(CharacterTableDisplay::Symbolic)
169        } else {
170            None
171        })
172        .infinite_order_to_finite(infinite_order_to_finite)
173        .build()
174        .map_err(|err| PyRuntimeError::new_err(err.to_string()))?;
175
176    let weight = weight.to_owned_array();
177    let grid_array = grid_points.to_owned_array();
178    if grid_array.shape()[0] != 3 {
179        return Err(PyRuntimeError::new_err(
180            "The grid point array does not have the expected dimensions of 3 × N.",
181        ));
182    }
183    let grid_points = grid_array
184        .columns()
185        .into_iter()
186        .map(|col| Point3::new(col[0], col[1], col[2]))
187        .collect::<Vec<_>>();
188
189    let real_space_function = RealSpaceFunction::<dtype_, _>::builder()
190        .function(|pt| {
191            Python::attach(|py_inner| {
192                let res = function.call1(py_inner, (pt.x, pt.y, pt.z)).expect(
193                    "Unable to apply the real-space function on the specified coordinates.",
194                );
195                res.extract::<dtype_>(py_inner)
196                    .expect("Unable to extract the result from the real-space function call.")
197            })
198        })
199        .grid_points(grid_points)
200        .build()
201        .map_err(|err| PyRuntimeError::new_err(err.to_string()))?;
202
203    match &use_magnetic_group {
204        Some(MagneticSymmetryAnalysisKind::Corepresentation) => {
205            let mut real_space_function_driver = RealSpaceFunctionRepAnalysisDriver::<
206                MagneticRepresentedSymmetryGroup,
207                dtype_,
208                _,
209            >::builder()
210            .parameters(&real_space_function_params)
211            .angular_function_parameters(&afa_params)
212            .real_space_function(&real_space_function)
213            .weight(&weight)
214            .symmetry_group(&pd_res)
215            .build()
216            .map_err(|err| PyRuntimeError::new_err(err.to_string()))?;
217            py.detach(|| {
218                real_space_function_driver
219                    .run()
220                    .map_err(|err| PyRuntimeError::new_err(err.to_string()))
221            })?
222        }
223        Some(MagneticSymmetryAnalysisKind::Representation) | None => {
224            let mut real_space_function_driver = RealSpaceFunctionRepAnalysisDriver::<
225                UnitaryRepresentedSymmetryGroup,
226                dtype_,
227                _,
228            >::builder()
229            .parameters(&real_space_function_params)
230            .angular_function_parameters(&afa_params)
231            .real_space_function(&real_space_function)
232            .weight(&weight)
233            .symmetry_group(&pd_res)
234            .build()
235            .map_err(|err| PyRuntimeError::new_err(err.to_string()))?;
236            py.detach(|| {
237                real_space_function_driver
238                    .run()
239                    .map_err(|err| PyRuntimeError::new_err(err.to_string()))
240            })?
241        }
242    };
243
244    Ok(())
245}