1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Python bindings for QSym² symmetry-group detection.
//!
//! See [`crate::drivers::symmetry_group_detection`] for more information.

use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;

use anyhow::{self, format_err};
use derive_builder::Builder;
use nalgebra::{Point3, Vector3};
use numpy::{PyArray1, ToPyArray};
use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;

use crate::auxiliary::atom::{Atom, ElementMap};
use crate::auxiliary::molecule::Molecule;
use crate::drivers::symmetry_group_detection::{
    SymmetryGroupDetectionDriver, SymmetryGroupDetectionParams,
};
use crate::drivers::QSym2Driver;
#[allow(unused_imports)]
use crate::io::QSym2FileType;
use crate::symmetry::symmetry_core::Symmetry;
use crate::symmetry::symmetry_element::{AntiunitaryKind, SymmetryElementKind};
use crate::symmetry::symmetry_element_order::ElementOrder;

// ===========================
// Struct and enum definitions
// ===========================

// ----------
// PyMolecule
// ----------

/// Python-exposed structure to marshall molecular structure information between Rust and Python.
///
/// # Constructor arguments
///
/// * `atoms` - The ordinary atoms in the molecule. Python type: `list[tuple[str, tuple[float,
/// float, float]]]`.
/// * `threshold` - Threshold for comparing molecules. Python type: `float`.
/// * `magnetic_field` - An optional uniform external magnetic field. Python type:
/// `Optional[tuple[float, float, float]]`.
/// * `electric_field` - An optional uniform external electric field. Python type:
/// `Optional[tuple[float, float, float]]`.
#[pyclass]
#[derive(Clone)]
pub struct PyMolecule {
    /// The ordinary atoms in the molecule.
    ///
    /// Python type: `list[tuple[str, tuple[float, float, float]]]`
    #[pyo3(get)]
    pub atoms: Vec<(String, [f64; 3])>,

    /// An optional uniform external magnetic field.
    ///
    /// Python type: `Optional[tuple[float, float, float]]`
    #[pyo3(get)]
    pub magnetic_field: Option<[f64; 3]>,

    /// An optional uniform external electric field.
    ///
    /// Python type: `Optional[tuple[float, float, float]]`
    #[pyo3(get)]
    pub electric_field: Option<[f64; 3]>,

    /// Threshold for comparing molecules.
    ///
    /// Python type: `float`
    #[pyo3(get)]
    pub threshold: f64,
}

#[pymethods]
impl PyMolecule {
    /// Creates a new `PyMolecule` structure.
    ///
    /// # Arguments
    ///
    /// * `atoms` - The ordinary atoms in the molecule. Python type: `list[tuple[str, tuple[float,
    /// float, float]]]`.
    /// * `threshold` - Threshold for comparing molecules. Python type: `float`.
    /// * `magnetic_field` - An optional uniform external magnetic field. Python type:
    /// `Optional[tuple[float, float, float]]`.
    /// * `electric_field` - An optional uniform external electric field. Python type:
    /// `Optional[tuple[float, float, float]]`.
    #[new]
    pub fn new(
        atoms: Vec<(String, [f64; 3])>,
        threshold: f64,
        magnetic_field: Option<[f64; 3]>,
        electric_field: Option<[f64; 3]>,
    ) -> Self {
        Self {
            atoms,
            threshold,
            magnetic_field,
            electric_field,
        }
    }
}

impl From<PyMolecule> for Molecule {
    fn from(pymol: PyMolecule) -> Self {
        let emap = ElementMap::new();
        let mut mol = Self::from_atoms(
            &pymol
                .atoms
                .iter()
                .map(|(ele, r)| {
                    Atom::new_ordinary(ele, Point3::new(r[0], r[1], r[2]), &emap, pymol.threshold)
                })
                .collect::<Vec<_>>(),
            pymol.threshold,
        );
        mol.set_magnetic_field(pymol.magnetic_field.map(Vector3::from_iterator));
        mol.set_electric_field(pymol.electric_field.map(Vector3::from_iterator));
        mol
    }
}

// ---------------------
// PySymmetryElementKind
// ---------------------

/// Python-exposed structure to marshall symmetry element kind information one-way from Rust to
/// Python.
#[pyclass]
#[derive(Clone, Hash, PartialEq, Eq)]
pub enum PySymmetryElementKind {
    /// Variant denoting proper symmetry elements.
    Proper,

    /// Variant denoting time-reversed proper symmetry elements.
    ProperTR,

    /// Variant denoting improper symmetry elements (mirror-plane convention).
    ImproperMirrorPlane,

    /// Variant denoting time-reversed improper symmetry elements (mirror-plane convention).
    ImproperMirrorPlaneTR,
}

impl fmt::Display for PySymmetryElementKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PySymmetryElementKind::Proper => write!(f, "Proper"),
            PySymmetryElementKind::ProperTR => write!(f, "Time-reversed proper"),
            PySymmetryElementKind::ImproperMirrorPlane => {
                write!(f, "Improper (mirror-plane convention)")
            }
            PySymmetryElementKind::ImproperMirrorPlaneTR => {
                write!(f, "Time-reversed improper (mirror-plane convention)")
            }
        }
    }
}

impl TryFrom<&SymmetryElementKind> for PySymmetryElementKind {
    type Error = anyhow::Error;

    fn try_from(symkind: &SymmetryElementKind) -> Result<Self, Self::Error> {
        match symkind {
            SymmetryElementKind::Proper(None) => Ok(Self::Proper),
            SymmetryElementKind::Proper(Some(AntiunitaryKind::TimeReversal)) => Ok(Self::ProperTR),
            SymmetryElementKind::ImproperMirrorPlane(None) => Ok(Self::ImproperMirrorPlane),
            SymmetryElementKind::ImproperMirrorPlane(Some(AntiunitaryKind::TimeReversal)) => {
                Ok(Self::ImproperMirrorPlaneTR)
            }
            _ => Err(format_err!(
                "Symmetry element kind `{symkind}` is not yet supported in Python."
            )),
        }
    }
}

// ----------
// PySymmetry
// ----------

/// Python-exposed structure to marshall symmetry information one-way from Rust to Python.
#[pyclass]
#[derive(Clone, Builder)]
pub struct PySymmetry {
    /// The name of the symmetry group.
    #[pyo3(get)]
    group_name: String,

    /// The symmetry elements.
    ///
    /// Python type: `dict[PySymmetryElementKind, dict[int, list[numpy.1darray[float]]]]`
    elements: HashMap<PySymmetryElementKind, HashMap<i32, Vec<Py<PyArray1<f64>>>>>,

    /// The symmetry generators.
    ///
    /// Python type: `dict[PySymmetryElementKind, dict[int, list[numpy.1darray[float]]]]`
    generators: HashMap<PySymmetryElementKind, HashMap<i32, Vec<Py<PyArray1<f64>>>>>,
}

impl PySymmetry {
    fn builder() -> PySymmetryBuilder {
        PySymmetryBuilder::default()
    }
}

#[pymethods]
impl PySymmetry {
    /// Returns a boolean indicating if the group is infinite.
    pub fn is_infinite(&self) -> bool {
        self.elements
            .values()
            .any(|kind_elements| kind_elements.contains_key(&-1))
            || self
                .generators
                .values()
                .any(|kind_generators| kind_generators.contains_key(&-1))
    }

    /// Returns symmetry elements of all *finite* orders of a given kind.
    ///
    /// # Arguments
    ///
    /// * `kind` - The symmetry element kind. Python type: `PySymmetryElementKind`.
    ///
    /// # Returns
    ///
    /// A hashmap where the keys are integers indicating the orders of the elements and the values
    /// are vectors of one-dimensional arrays, each of which gives the axis of a symmetry element.
    /// If the order value is `-1`, then the associated elements have infinite order.
    ///
    /// Python type: `dict[int, list[numpy.1darray[float]]]`.
    pub fn get_elements_of_kind(
        &self,
        kind: &PySymmetryElementKind,
    ) -> PyResult<HashMap<i32, Vec<Py<PyArray1<f64>>>>> {
        self.elements
            .get(kind)
            .cloned()
            .ok_or(PyRuntimeError::new_err(format!(
                "Elements of kind `{kind}` not found."
            )))
    }

    /// Returns symmetry generators of *finite*  and *infinite* orders of a given kind.
    ///
    /// # Arguments
    ///
    /// * `kind` - The symmetry generator kind. Python type: `PySymmetryElementKind`.
    ///
    /// # Returns
    ///
    /// A hashmap where the keys are integers indicating the orders of the generators and the values
    /// are vectors of one-dimensional arrays, each of which gives the axis of a symmetry generator.
    /// If the order value is `-1`, then the associated generators have infinite order.
    ///
    /// Python type: `dict[int, list[numpy.1darray[float]]]`.
    pub fn get_generators_of_kind(
        &self,
        kind: &PySymmetryElementKind,
    ) -> PyResult<HashMap<i32, Vec<Py<PyArray1<f64>>>>> {
        self.generators
            .get(kind)
            .cloned()
            .ok_or(PyRuntimeError::new_err(format!(
                "Elements of kind `{kind}` not found."
            )))
    }
}

impl TryFrom<&Symmetry> for PySymmetry {
    type Error = anyhow::Error;

    fn try_from(sym: &Symmetry) -> Result<Self, Self::Error> {
        let group_name = sym
            .group_name
            .clone()
            .ok_or(format_err!("Symmetry group name not found."))?;
        let elements = sym
            .elements
            .iter()
            .map(|(symkind, kind_elements)| {
                let pysymkind = PySymmetryElementKind::try_from(symkind)?;
                let pykind_elements = kind_elements
                    .iter()
                    .map(|(order, order_elements)| {
                        let order_i32 = match order {
                            ElementOrder::Int(ord) => i32::try_from(*ord)?,
                            ElementOrder::Inf => -1,
                        };
                        let pyorder_elements = order_elements
                            .iter()
                            .map(|ele| {
                                Python::with_gil(|py| {
                                    ele.raw_axis()
                                        .iter()
                                        .cloned()
                                        .collect::<Vec<_>>()
                                        .to_pyarray_bound(py)
                                        .unbind()
                                })
                            })
                            .collect::<Vec<_>>();
                        Ok::<_, Self::Error>((order_i32, pyorder_elements))
                    })
                    .collect::<Result<HashMap<i32, Vec<_>>, _>>()?;
                Ok::<_, Self::Error>((pysymkind, pykind_elements))
            })
            .collect::<Result<HashMap<_, _>, _>>()?;

        let generators = sym
            .generators
            .iter()
            .map(|(symkind, kind_generators)| {
                let pysymkind = PySymmetryElementKind::try_from(symkind)?;
                let pykind_generators = kind_generators
                    .iter()
                    .map(|(order, order_generators)| {
                        let order_i32 = match order {
                            ElementOrder::Int(ord) => i32::try_from(*ord)?,
                            ElementOrder::Inf => -1,
                        };
                        let pyorder_generators = order_generators
                            .iter()
                            .map(|ele| {
                                Python::with_gil(|py| {
                                    ele.raw_axis()
                                        .iter()
                                        .cloned()
                                        .collect::<Vec<_>>()
                                        .to_pyarray_bound(py)
                                        .unbind()
                                })
                            })
                            .collect::<Vec<_>>();
                        Ok::<_, Self::Error>((order_i32, pyorder_generators))
                    })
                    .collect::<Result<HashMap<i32, Vec<_>>, _>>()?;
                Ok::<_, Self::Error>((pysymkind, pykind_generators))
            })
            .collect::<Result<HashMap<_, _>, _>>()?;

        PySymmetry::builder()
            .group_name(group_name)
            .elements(elements)
            .generators(generators)
            .build()
            .map_err(|err| format_err!(err))
    }
}

// =========
// Functions
// =========

/// Python-exposed function to perform symmetry-group detection and log the result via the
/// `qsym2-output` logger at the `INFO` level.
///
/// See [`crate::drivers::symmetry_group_detection`] for more information.
///
/// # Arguments
///
/// * `inp_xyz` - An optional string providing the path to an XYZ file containing the molecule to
/// be analysed. Only one of `inp_xyz` or `inp_mol` can be specified. Python type: `Optional[str]`.
/// * `inp_mol` - An optional `PyMolecule` structure containing the molecule to be analysed. Only
/// one of `inp_xyz` or `inp_mol` can be specified. Python type: `PyMolecule`.
/// * `out_sym` - An optional name for the [`QSym2FileType::Sym`] file to be saved that contains
/// the serialised results of the symmetry-group detection. Python type: `Optional[str]`.
/// * `moi_thresholds` - Thresholds for comparing moments of inertia. Python type: `list[float]`.
/// * `distance_thresholds` - Thresholds for comparing distances. Python type: `list[float]`.
/// * `time_reversal` - A boolean indicating whether elements involving time reversal should also
/// be considered. Python type: `bool`.
/// * `write_symmetry_elements` - A boolean indicating if detected symmetry elements should be
/// printed in the output. Python type: `bool`.
/// * `fictitious_magnetic_field` - An optional fictitious uniform external magnetic field. Python
/// type: `Optional[tuple[float, float, float]]`.
/// * `fictitious_electric_field` - An optional fictitious uniform external electric field. Python
/// type: `Optional[tuple[float, float, float]]`.
///
/// # Errors
///
/// Returns an error if any intermediate step in the symmetry-group detection procedure fails.
#[pyfunction]
#[pyo3(signature = (
    inp_xyz,
    inp_mol,
    out_sym,
    moi_thresholds,
    distance_thresholds,
    time_reversal,
    write_symmetry_elements=true,
    fictitious_magnetic_field=None,
    fictitious_electric_field=None,
))]
pub fn detect_symmetry_group(
    py: Python<'_>,
    inp_xyz: Option<PathBuf>,
    inp_mol: Option<PyMolecule>,
    out_sym: Option<PathBuf>,
    moi_thresholds: Vec<f64>,
    distance_thresholds: Vec<f64>,
    time_reversal: bool,
    write_symmetry_elements: bool,
    fictitious_magnetic_field: Option<[f64; 3]>,
    fictitious_electric_field: Option<[f64; 3]>,
) -> PyResult<(PySymmetry, Option<PySymmetry>)> {
    py.allow_threads(|| {
        let params = SymmetryGroupDetectionParams::builder()
            .distance_thresholds(&distance_thresholds)
            .moi_thresholds(&moi_thresholds)
            .time_reversal(time_reversal)
            .fictitious_magnetic_fields(
                fictitious_magnetic_field
                    .map(|bs| vec![(Point3::<f64>::origin(), Vector3::new(bs[0], bs[1], bs[2]))]),
            )
            .fictitious_electric_fields(
                fictitious_electric_field
                    .map(|es| vec![(Point3::<f64>::origin(), Vector3::new(es[0], es[1], es[2]))]),
            )
            .field_origin_com(true)
            .write_symmetry_elements(write_symmetry_elements)
            .result_save_name(out_sym)
            .build()
            .map_err(|err| PyRuntimeError::new_err(err.to_string()))?;
        let inp_mol = inp_mol.map(Molecule::from);
        let mut pd_driver = SymmetryGroupDetectionDriver::builder()
            .parameters(&params)
            .xyz(inp_xyz)
            .molecule(inp_mol.as_ref())
            .build()
            .map_err(|err| PyRuntimeError::new_err(err.to_string()))?;
        pd_driver
            .run()
            .map_err(|err| PyRuntimeError::new_err(err.to_string()))?;
        let pyunitary_symmetry: PySymmetry = (&pd_driver
            .result()
            .map_err(|err| PyRuntimeError::new_err(err.to_string()))?
            .unitary_symmetry)
            .try_into()
            .map_err(|err: anyhow::Error| PyRuntimeError::new_err(err.to_string()))?;
        let pymagnetic_symmetry: Option<PySymmetry> = pd_driver
            .result()
            .map_err(|err| PyRuntimeError::new_err(err.to_string()))?
            .magnetic_symmetry
            .as_ref()
            .map(|magsym| {
                magsym
                    .try_into()
                    .map_err(|err: anyhow::Error| PyRuntimeError::new_err(err.to_string()))
            })
            .transpose()?;
        Ok((pyunitary_symmetry, pymagnetic_symmetry))
    })
}