molio 0.4.1

A library for reading chemical file formats
Documentation
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2025 William Bro-Jørgensen
// Copyright (c) 2020 Guillaume Fraux and contributors
//
// See LICENSE at the project root for full text.

use crate::error::CError;
use core::f64;
use nalgebra::Matrix3;
use std::ops::Index;

#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct Vec3D([f64; 3]);

impl From<[f64; 3]> for Vec3D {
    fn from(value: [f64; 3]) -> Self {
        Vec3D(value)
    }
}

impl AsRef<[f64; 3]> for Vec3D {
    fn as_ref(&self) -> &[f64; 3] {
        &self.0
    }
}

impl AsMut<[f64; 3]> for Vec3D {
    fn as_mut(&mut self) -> &mut [f64; 3] {
        &mut self.0
    }
}

impl Index<usize> for Vec3D {
    type Output = f64;
    fn index(&self, i: usize) -> &f64 {
        &self.0[i]
    }
}

#[derive(Debug, PartialEq, Eq, Default, Hash)]
pub enum CellShape {
    #[default]
    Orthorhombic,
    Triclinic,
    Infinite,
}

mod utils {
    use super::Vec3D;
    use nalgebra::Matrix3;

    /// Check if a value is approximately zero (within 1e-5)
    pub fn is_roughly_zero(x: f64) -> bool {
        x.abs() < 1e-5
    }

    /// Check if an angle is approximately 90 degrees (within 1e-3)
    pub fn is_roughly_90(value: f64) -> bool {
        (value - 90.0).abs() < 1e-3
    }

    /// Calculate the lengths of the cell vectors from the matrix
    pub fn calc_lengths_from_matrix(matrix: Matrix3<f64>) -> Vec3D {
        let v1 = matrix.row(0);
        let v2 = matrix.row(1);
        let v3 = matrix.row(2);

        Vec3D([v1.norm(), v2.norm(), v3.norm()])
    }

    /// Calculate the angles between cell vectors from the matrix
    pub fn calc_angles_from_matrix(matrix: Matrix3<f64>) -> Vec3D {
        let v1 = matrix.row(0);
        let v2 = matrix.row(1);
        let v3 = matrix.row(2);

        Vec3D([
            (v2.dot(&v3) / (v2.norm() * v3.norm())).acos().to_degrees(),
            (v1.dot(&v3) / (v1.norm() * v3.norm())).acos().to_degrees(),
            (v1.dot(&v2) / (v1.norm() * v2.norm())).acos().to_degrees(),
        ])
    }

    /// Calculate cosine of an angle in degrees
    pub fn cos_degree(theta: f64) -> f64 {
        theta.to_radians().cos()
    }

    /// Calculate sine of an angle in degrees
    pub fn sin_degree(theta: f64) -> f64 {
        theta.to_radians().sin()
    }

    /// Check if a cell is orthorhombic based on its lengths and angles
    pub fn is_orthorhombic(lengths: Vec3D, angles: Vec3D) -> bool {
        if is_infinite(lengths) {
            return false;
        }

        // we support cells with one or two lengths of 0 which results in NaN angles
        angles
            .as_ref()
            .iter()
            .all(|&angle| is_roughly_90(angle) || angle.is_nan())
    }

    /// Check if a cell is infinite (all lengths are zero)
    pub fn is_infinite(lengths: Vec3D) -> bool {
        lengths.as_ref().iter().all(|&x| is_roughly_zero(x))
    }

    /// Check if a matrix is diagonal (all off-diagonal elements are zero)
    pub fn is_diagonal(matrix: Matrix3<f64>) -> bool {
        matrix
            .iter()
            .enumerate()
            .filter(|(i, _)| i % 4 != 0) // Skip diagonal elements
            .all(|(_, &x)| is_roughly_zero(x))
    }
}

mod validation {
    use super::{CError, Vec3D, utils};

    /// Validate cell angles
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any length is negative
    pub fn check_lengths(lengths: Vec3D) -> Result<(), CError> {
        if let Some(&length) = lengths.as_ref().iter().find(|&&x| x < 0.0) {
            return Err(CError::GenericError(format!(
                "negative length found: {length}"
            )));
        }

        Ok(())
    }

    /// Validate cell angles
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Any angle is negative
    /// - Any angle is zero
    /// - Any angle is 180 degrees or greater
    pub fn check_angles(angles: Vec3D) -> Result<(), CError> {
        if let Some(&angle) = angles.as_ref().iter().find(|&&x| x < 0.0) {
            return Err(CError::GenericError(format!(
                "negative angle found: {angle}"
            )));
        }

        if let Some(&angle) = angles.as_ref().iter().find(|&&x| utils::is_roughly_zero(x)) {
            return Err(CError::GenericError(format!("zero angle found: {angle}")));
        }

        if let Some(&angle) = angles.as_ref().iter().find(|&&x| x >= 180.0) {
            return Err(CError::GenericError(format!("angle too large: {angle}")));
        }

        Ok(())
    }
}

mod matrix {
    use super::{CError, Matrix3, Vec3D, utils, validation};

    /// Create a cell matrix from lengths and angles
    ///
    /// # Errors
    ///
    /// Returns an error if the lengths or angles are invalid
    pub fn cell_matrix_from_lengths_angles(
        lengths: Vec3D,
        // TODO: probably this shouldn't be mut
        angles: Vec3D,
    ) -> Result<Matrix3<f64>, CError> {
        validation::check_lengths(lengths)?;
        validation::check_angles(angles)?;
        let mut angles = angles;

        // Normalize angles to 90 degrees if they're close enough
        if angles.as_ref().iter().all(|&x| utils::is_roughly_90(x)) {
            for x in angles.as_mut().iter_mut() {
                *x = 90.0;
            }
        }

        let mut cell_matrix = Matrix3::zeros();
        cell_matrix[(0, 0)] = lengths[0];

        let cos_gamma = utils::cos_degree(angles[2]);
        let sin_gamma = utils::sin_degree(angles[2]);
        cell_matrix[(1, 0)] = cos_gamma * lengths[1];
        cell_matrix[(1, 1)] = sin_gamma * lengths[1];

        let cos_beta = utils::cos_degree(angles[1]);
        let cos_alpha = utils::cos_degree(angles[0]);

        cell_matrix[(2, 0)] = cos_beta;
        cell_matrix[(2, 1)] = (cos_alpha - cos_beta * cos_gamma) / sin_gamma;
        cell_matrix[(2, 2)] =
            (1.0 - cell_matrix[(2, 0)].powi(2) - cell_matrix[(2, 1)].powi(2)).sqrt();
        cell_matrix[(2, 0)] *= lengths[2];
        cell_matrix[(2, 1)] *= lengths[2];
        cell_matrix[(2, 2)] *= lengths[2];

        Ok(cell_matrix)
    }
}

#[derive(Debug, Default)]
pub struct UnitCell {
    pub matrix: Matrix3<f64>,
    pub shape: CellShape,
    pub matrix_inv_transposed: Option<Matrix3<f64>>,
}

impl PartialEq for UnitCell {
    fn eq(&self, other: &Self) -> bool {
        self.matrix
            .iter()
            .zip(other.matrix.iter())
            .all(|(a, b)| (a - b).abs() < f64::EPSILON)
    }
}

impl Eq for UnitCell {}

impl UnitCell {
    #[must_use]
    pub fn new() -> Self {
        UnitCell::new_from_lengths(Vec3D([0.0, 0.0, 0.0]))
    }

    #[must_use]
    pub fn new_from_lengths(lengths: Vec3D) -> Self {
        UnitCell::new_from_lengths_angles(lengths, Vec3D([90.0, 90.0, 90.0])).unwrap()
    }

    /// # Errors
    ///
    /// Returns an error if:
    /// - Any length is negative
    /// - Any angle is negative
    /// - Any angle is zero
    /// - Any angle is 180 degrees or greater
    pub fn new_from_lengths_angles(lengths: Vec3D, angles: Vec3D) -> Result<Self, CError> {
        let matrix = matrix::cell_matrix_from_lengths_angles(lengths, angles)?;
        Self::new_from_matrix(matrix)
    }

    /// # Errors
    ///
    /// Will return `Err` if the determinant of the input matrix < 0.0
    ///
    /// Will return `Err` if the input matrix [`CellShape::Orthorhombic`], but
    /// not diagonal
    pub fn new_from_matrix(matrix: Matrix3<f64>) -> Result<Self, CError> {
        let mut matrix = matrix;
        if matrix.determinant() < 0.0 {
            return Err(CError::GenericError(
                "invalid unit cell matrix with negative determinant".to_string(),
            ));
        }

        let lengths = utils::calc_lengths_from_matrix(matrix);
        let angles = utils::calc_angles_from_matrix(matrix);

        let is_diagonal_matrix = utils::is_diagonal(matrix);
        if !is_diagonal_matrix && utils::is_orthorhombic(lengths, angles) {
            return Err(CError::GenericError("orthorhombic cell must have their a vector along x axis, b vector along y axis and c vector along z axis".to_string()));
        }

        let shape = if is_diagonal_matrix {
            if matrix.diagonal().iter().all(|&x| utils::is_roughly_zero(x)) {
                matrix = Matrix3::zeros();
                CellShape::Infinite
            } else {
                CellShape::Orthorhombic
            }
        } else {
            CellShape::Triclinic
        };

        let matrix_inv_transposed = matrix.try_inverse().map(|m| m.transpose());

        Ok(UnitCell {
            matrix,
            shape,
            matrix_inv_transposed,
        })
    }

    #[must_use]
    pub fn lengths(&self) -> Vec3D {
        match self.shape {
            CellShape::Infinite => Vec3D([0.0, 0.0, 0.0]),
            CellShape::Orthorhombic => Vec3D([
                self.matrix[(0, 0)],
                self.matrix[(1, 1)],
                self.matrix[(2, 2)],
            ]),
            CellShape::Triclinic => utils::calc_lengths_from_matrix(self.matrix),
        }
    }

    #[must_use]
    pub fn angles(&self) -> Vec3D {
        match self.shape {
            CellShape::Infinite | CellShape::Orthorhombic => Vec3D([90.0, 90.0, 90.0]),
            CellShape::Triclinic => utils::calc_angles_from_matrix(self.matrix),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_approx_eq::assert_approx_eq;
    use nalgebra::Matrix3;

    #[test]
    fn test_unit_cell_new() {
        let cell = UnitCell::new();
        assert_eq!(cell.matrix, Matrix3::zeros());
        assert_eq!(cell.shape, CellShape::Infinite);
        assert!(cell.matrix_inv_transposed.is_none());
    }

    #[test]
    fn test_unit_cell_from_lengths() {
        let lengths = [10.0, 20.0, 30.0];
        let cell = UnitCell::new_from_lengths(lengths.into());
        assert_approx_eq!(cell.matrix[(0, 0)], 10.0);
        assert_approx_eq!(cell.matrix[(1, 1)], 20.0);
        assert_approx_eq!(cell.matrix[(2, 2)], 30.0);
        assert_eq!(cell.shape, CellShape::Orthorhombic);
    }

    #[test]
    fn test_unit_cell_from_lengths_angles() {
        let lengths = [10.0, 20.0, 30.0];
        let angles = [90.0, 90.0, 90.0];
        let cell = UnitCell::new_from_lengths_angles(lengths.into(), angles.into()).unwrap();
        assert_approx_eq!(cell.matrix[(0, 0)], 10.0);
        assert_approx_eq!(cell.matrix[(1, 1)], 20.0);
        assert_approx_eq!(cell.matrix[(2, 2)], 30.0);
        assert_eq!(cell.shape, CellShape::Orthorhombic);
    }

    #[test]
    fn test_unit_cell_from_matrix() {
        let mut matrix = Matrix3::zeros();
        matrix[(0, 0)] = 10.0;
        matrix[(1, 1)] = 20.0;
        matrix[(2, 2)] = 30.0;
        let cell = UnitCell::new_from_matrix(matrix).unwrap();
        assert_eq!(cell.matrix, matrix);
        assert_eq!(cell.shape, CellShape::Orthorhombic);
    }

    #[test]
    fn test_unit_cell_lengths() {
        let cell = UnitCell::new_from_lengths([10.0, 20.0, 30.0].into());
        let expected = [10.0, 20.0, 30.0];
        for (t, e) in expected.iter().zip(cell.lengths().as_ref().iter()) {
            assert_approx_eq!(t, e);
        }
    }

    #[test]
    fn test_unit_cell_angles() {
        let cell = UnitCell::new_from_lengths([10.0, 20.0, 30.0].into());
        for i in 0..3 {
            assert_approx_eq!(cell.angles()[i], 90.0);
        }
    }

    #[test]
    fn test_check_lengths_valid() {
        let lengths = [1.0, 2.0, 3.0];
        assert!(validation::check_lengths(lengths.into()).is_ok());
    }

    #[test]
    #[should_panic(expected = "negative length found: -1")]
    fn test_check_lengths_invalid_first_negative() {
        let lengths = [-1.0, 2.0, 3.0];
        validation::check_lengths(lengths.into()).unwrap();
    }

    #[test]
    fn test_check_angles_valid() {
        let angles = [90.0, 90.0, 90.0];
        assert!(validation::check_angles(angles.into()).is_ok());
    }

    #[test]
    fn test_check_angles_valid_non_orthogonal() {
        let angles = [60.0, 60.0, 60.0];
        assert!(validation::check_angles(angles.into()).is_ok());
    }

    #[test]
    #[should_panic(expected = "negative angle found: -90")]
    fn test_check_angles_invalid_negative() {
        let angles = [-90.0, 90.0, 90.0];
        validation::check_angles(angles.into()).unwrap();
    }

    #[test]
    #[should_panic(expected = "zero angle found: 0")]
    fn test_check_angles_invalid_zero() {
        let angles = [0.0, 90.0, 90.0];
        validation::check_angles(angles.into()).unwrap();
    }

    #[test]
    #[should_panic(expected = "angle too large: 180")]
    fn test_check_angles_invalid_180_and_greater() {
        let angles = [180.0, 90.0, 90.0];
        validation::check_angles(angles.into()).unwrap();
        let angles = [200.0, 90.0, 90.0];
        validation::check_angles(angles.into()).unwrap();
    }

    #[test]
    fn test_cell_matrix_from_lengths_angles_valid() {
        let lengths = [10.0, 20.0, 30.0];
        let angles = [90.0, 90.0, 90.0];
        let matrix =
            matrix::cell_matrix_from_lengths_angles(lengths.into(), angles.into()).unwrap();
        assert_approx_eq!(matrix[(0, 0)], 10.0);
        assert_approx_eq!(matrix[(1, 1)], 20.0);
        assert_approx_eq!(matrix[(2, 2)], 30.0);
    }

    #[test]
    fn test_cell_matrix_from_lengths_angles_triclinic() {
        let lengths = [10.0, 20.0, 30.0];
        let angles = [60.0, 60.0, 60.0];
        let matrix =
            matrix::cell_matrix_from_lengths_angles(lengths.into(), angles.into()).unwrap();
        assert!(!utils::is_diagonal(matrix));
    }

    #[test]
    fn test_is_orthorhombic() {
        let lengths = [10.0, 20.0, 30.0];
        let angles = [90.0, 90.0, 90.0];
        assert!(utils::is_orthorhombic(lengths.into(), angles.into()));
    }

    #[test]
    fn test_is_orthorhombic_with_nan() {
        let lengths = [10.0, 20.0, 0.0];
        let angles = [90.0, 90.0, f64::NAN];
        assert!(utils::is_orthorhombic(lengths.into(), angles.into()));
    }

    #[test]
    fn test_is_infinite() {
        let lengths = [0.0, 0.0, 0.0];
        assert!(utils::is_infinite(lengths.into()));
    }

    #[test]
    fn test_is_diagonal() {
        let mut matrix = Matrix3::zeros();
        matrix[(0, 0)] = 1.0;
        matrix[(1, 1)] = 2.0;
        matrix[(2, 2)] = 3.0;
        assert!(utils::is_diagonal(matrix));
    }

    #[test]
    fn test_is_not_diagonal() {
        let mut matrix = Matrix3::zeros();
        matrix[(0, 0)] = 1.0;
        matrix[(1, 1)] = 2.0;
        matrix[(2, 2)] = 3.0;
        matrix[(0, 1)] = 0.1;
        assert!(!utils::is_diagonal(matrix));
    }

    #[test]
    fn from_lengths_angles() {
        let expected = UnitCell::new_from_lengths_angles(
            [8.431_160_35, 14.505_106_13, 15.609_114_68].into(),
            [73.316_992_12, 85.702_005_82, 89.375_015_29].into(),
        )
        .unwrap();
        let mut true_cell = UnitCell::new();
        true_cell.matrix[(0, 0)] = 8.431_160_35;
        true_cell.matrix[(1, 0)] = 0.158_219_155_128;
        true_cell.matrix[(1, 1)] = 14.504_243_186_3;
        true_cell.matrix[(2, 0)] = 1.169_806_636_24;
        true_cell.matrix[(2, 1)] = 4.468_514_985_5;
        true_cell.matrix[(2, 2)] = 14.910_009_640_5;
        let diff = expected.matrix - true_cell.matrix;
        assert!((diff).iter().all(|&x| x.abs() < 1e-6), "diff: {diff}");
    }
}