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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
// Chemfiles, a modern library for chemistry file reading and writing
// Copyright (C) 2015-2018 Guillaume Fraux -- BSD licensed
use std::marker::PhantomData;

use chemfiles_sys::*;

use crate::errors::{check, check_not_null, check_success, Error};

/// Available unit cell shapes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CellShape {
    /// Orthorhombic cell, with the three angles equals to 90°.
    Orthorhombic,
    /// Triclinic cell, with any values for the angles.
    Triclinic,
    /// Infinite cell, to use when there is no cell.
    Infinite,
}

impl From<chfl_cellshape> for CellShape {
    fn from(celltype: chfl_cellshape) -> CellShape {
        match celltype {
            chfl_cellshape::CHFL_CELL_ORTHORHOMBIC => CellShape::Orthorhombic,
            chfl_cellshape::CHFL_CELL_TRICLINIC => CellShape::Triclinic,
            chfl_cellshape::CHFL_CELL_INFINITE => CellShape::Infinite,
        }
    }
}

impl From<CellShape> for chfl_cellshape {
    fn from(celltype: CellShape) -> chfl_cellshape {
        match celltype {
            CellShape::Orthorhombic => chfl_cellshape::CHFL_CELL_ORTHORHOMBIC,
            CellShape::Triclinic => chfl_cellshape::CHFL_CELL_TRICLINIC,
            CellShape::Infinite => chfl_cellshape::CHFL_CELL_INFINITE,
        }
    }
}

/// An `UnitCell` represent the box containing the atoms, and its periodicity.
///
/// An unit cell is fully represented by three lengths (a, b, c); and three
/// angles (alpha, beta, gamma). The angles are stored in degrees, and the
/// lengths in Angstroms.
///
/// A cell also has a matricial representation, by projecting the three base
/// vector into an orthonormal base. We choose to represent such matrix as an
/// upper triangular matrix:
///
/// ```text
/// | a_x   b_x   c_x |
/// |  0    b_y   c_y |
/// |  0     0    c_z |
/// ```
#[derive(Debug)]
pub struct UnitCell {
    handle: *mut CHFL_CELL,
}

/// An analog to a reference to an unit cell (`&UnitCell`)
#[derive(Debug)]
pub struct UnitCellRef<'a> {
    inner: UnitCell,
    marker: PhantomData<&'a UnitCell>,
}

impl<'a> std::ops::Deref for UnitCellRef<'a> {
    type Target = UnitCell;
    fn deref(&self) -> &UnitCell {
        &self.inner
    }
}

/// An analog to a mutable reference to an unit cell (`&mut UnitCell`)
#[derive(Debug)]
pub struct UnitCellMut<'a> {
    inner: UnitCell,
    marker: PhantomData<&'a mut UnitCell>,
}

impl<'a> std::ops::Deref for UnitCellMut<'a> {
    type Target = UnitCell;
    fn deref(&self) -> &UnitCell {
        &self.inner
    }
}

impl<'a> std::ops::DerefMut for UnitCellMut<'a> {
    fn deref_mut(&mut self) -> &mut UnitCell {
        &mut self.inner
    }
}

impl Clone for UnitCell {
    fn clone(&self) -> UnitCell {
        unsafe {
            let new_handle = chfl_cell_copy(self.as_ptr());
            UnitCell::from_ptr(new_handle)
        }
    }
}

impl UnitCell {
    /// Create an owned `UnitCell` from a C pointer.
    ///
    /// This function is unsafe because no validity check is made on the pointer.
    #[inline]
    pub(crate) unsafe fn from_ptr(ptr: *mut CHFL_CELL) -> UnitCell {
        check_not_null(ptr);
        UnitCell { handle: ptr }
    }

    /// Create a borrowed `UnitCell` from a C pointer.
    ///
    /// This function is unsafe because no validity check is made on the
    /// pointer, and the caller is responsible for setting the right lifetime.
    #[inline]
    pub(crate) unsafe fn ref_from_ptr<'a>(ptr: *const CHFL_CELL) -> UnitCellRef<'a> {
        UnitCellRef {
            inner: UnitCell::from_ptr(ptr as *mut CHFL_CELL),
            marker: PhantomData,
        }
    }

    /// Create a borrowed `UnitCell` from a C pointer.
    ///
    /// This function is unsafe because no validity check is made on the
    /// pointer, except for it being non-null, and the caller is responsible for
    /// setting the right lifetime
    #[inline]
    pub(crate) unsafe fn ref_mut_from_ptr<'a>(ptr: *mut CHFL_CELL) -> UnitCellMut<'a> {
        UnitCellMut {
            inner: UnitCell::from_ptr(ptr),
            marker: PhantomData,
        }
    }

    /// Get the underlying C pointer as a const pointer.
    #[inline]
    pub(crate) fn as_ptr(&self) -> *const CHFL_CELL {
        self.handle
    }

    /// Get the underlying C pointer as a mutable pointer.
    #[inline]
    pub(crate) fn as_mut_ptr(&mut self) -> *mut CHFL_CELL {
        self.handle
    }

    /// Create an `Orthorhombic` `UnitCell` from the three lengths, in Angstroms.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{UnitCell, CellShape};
    /// let cell = UnitCell::new([30.0, 30.0, 23.0]);
    ///
    /// assert_eq!(cell.lengths(), [30.0, 30.0, 23.0]);
    /// assert_eq!(cell.angles(), [90.0, 90.0, 90.0]);
    /// assert_eq!(cell.shape(), CellShape::Orthorhombic);
    /// ```
    pub fn new(lengths: [f64; 3]) -> UnitCell {
        unsafe {
            let handle = chfl_cell(lengths.as_ptr(), std::ptr::null());
            UnitCell::from_ptr(handle)
        }
    }

    /// Create an `Infinite` `UnitCell`.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{UnitCell, CellShape};
    /// let cell = UnitCell::infinite();
    ///
    /// assert_eq!(cell.lengths(), [0.0, 0.0, 0.0]);
    /// assert_eq!(cell.angles(), [90.0, 90.0, 90.0]);
    /// assert_eq!(cell.shape(), CellShape::Infinite);
    /// ```
    pub fn infinite() -> UnitCell {
        let mut cell = UnitCell::new([0.0, 0.0, 0.0]);
        cell.set_shape(CellShape::Infinite).expect("could not set cell shape");
        return cell;
    }

    /// Create an `Triclinic` `UnitCell` from the three lengths (in Angstroms)
    /// and three angles (in degree). `alpha` is the angle between the vectors
    /// `b` and `c`; `beta` is the between the vectors `a` and `c` and `gamma`
    /// is the angle between the vectors `a` and `b`.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{UnitCell, CellShape};
    /// let cell = UnitCell::triclinic([10.0, 10.0, 10.0], [98.0, 99.0, 90.0]);
    ///
    /// assert_eq!(cell.lengths(), [10.0, 10.0, 10.0]);
    /// assert_eq!(cell.angles()[0], 98.0);
    /// // Rounding errors might occur due to internal representation
    /// assert!((cell.angles()[1] - 99.0).abs() < 1e-12);
    /// assert_eq!(cell.angles()[2], 90.0);
    /// assert_eq!(cell.shape(), CellShape::Triclinic);
    /// ```
    pub fn triclinic(lengths: [f64; 3], angles: [f64; 3]) -> UnitCell {
        unsafe {
            let handle = chfl_cell(lengths.as_ptr(), angles.as_ptr());
            UnitCell::from_ptr(handle)
        }
    }

    /// Create an `UnitCell` from a cell matrix. If `matrix` contains only
    /// zeros, then an `Infinite` cell is created. If only the diagonal of the
    /// matrix is non-zero, then the cell is `Orthorhombic`. Else a
    /// `Triclinic` cell is created. The matrix entries should be in Angstroms.
    ///
    /// # Panics
    ///
    /// If the matrix has a negative determinant, or more generally is not
    /// representing a unit cell.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{UnitCell, CellShape};
    /// let cell = UnitCell::from_matrix([
    ///     [1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0]
    /// ]);
    ///
    /// assert_eq!(cell.lengths(), [1.0, 2.0, 3.0]);
    /// assert_eq!(cell.angles(), [90.0, 90.0, 90.0]);
    /// assert_eq!(cell.shape(), CellShape::Orthorhombic);
    /// ```
    pub fn from_matrix(mut matrix: [[f64; 3]; 3]) -> UnitCell {
        unsafe {
            let handle = chfl_cell_from_matrix(matrix.as_mut_ptr());
            UnitCell::from_ptr(handle)
        }
    }

    /// Get the three lengths of the cell, in Angstroms.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::UnitCell;
    /// let cell = UnitCell::new([30.0, 30.0, 23.0]);
    /// assert_eq!(cell.lengths(), [30.0, 30.0, 23.0]);
    /// ```
    pub fn lengths(&self) -> [f64; 3] {
        let mut lengths = [0.0; 3];
        unsafe {
            check_success(chfl_cell_lengths(self.as_ptr(), lengths.as_mut_ptr()));
        }
        return lengths;
    }

    /// Set the three lengths of the cell, in Angstroms.
    ///
    /// # Errors
    ///
    /// This function fails if the unit cell is infinite, or if one of the
    /// lengths is negative.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::UnitCell;
    /// let mut cell = UnitCell::new([30.0, 30.0, 23.0]);
    ///
    /// cell.set_lengths([10.0, 30.0, 42.0]).unwrap();
    /// assert_eq!(cell.lengths(), [10.0, 30.0, 42.0]);
    ///
    /// assert!(UnitCell::infinite().set_lengths([1.0, 1.0, 1.0]).is_err());
    /// ```
    pub fn set_lengths(&mut self, lengths: [f64; 3]) -> Result<(), Error> {
        unsafe { check(chfl_cell_set_lengths(self.as_mut_ptr(), lengths.as_ptr())) }
    }

    /// Get the three angles of the cell, in degrees.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::UnitCell;
    /// let cell = UnitCell::new([20.0, 20.0, 20.0]);
    /// assert_eq!(cell.angles(), [90.0, 90.0, 90.0]);
    ///
    /// let cell = UnitCell::triclinic([20.0, 20.0, 20.0], [100.0, 120.0, 90.0]);
    /// assert_eq!(cell.angles()[0], 100.0);
    /// // Rounding errors might occur due to internal representation
    /// assert!((cell.angles()[1] - 120.0).abs() < 1e-12);
    /// assert_eq!(cell.angles()[2], 90.0);
    /// ```
    pub fn angles(&self) -> [f64; 3] {
        let mut angles = [0.0; 3];
        unsafe {
            check_success(chfl_cell_angles(self.as_ptr(), angles.as_mut_ptr()));
        }
        return angles;
    }

    /// Set the three angles of the cell, in degrees.
    ///
    /// # Errors
    ///
    /// This function fails if the unit cell is not `Triclinic`.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::UnitCell;
    /// let mut cell = UnitCell::triclinic([20.0, 20.0, 20.0], [100.0, 120.0, 90.0]);
    /// assert_eq!(cell.angles()[0], 100.0);
    /// // Rounding errors might occur due to internal representation
    /// assert!((cell.angles()[1] - 120.0).abs() < 1e-12);
    /// assert_eq!(cell.angles()[2], 90.0);
    ///
    /// cell.set_angles([90.0, 90.0, 90.0]).unwrap();
    /// assert_eq!(cell.angles(), [90.0, 90.0, 90.0]);
    /// ```
    pub fn set_angles(&mut self, angles: [f64; 3]) -> Result<(), Error> {
        unsafe { check(chfl_cell_set_angles(self.as_mut_ptr(), angles.as_ptr())) }
    }

    /// Get the unit cell matricial representation.
    ///
    /// The unit cell representation is obtained by aligning the a vector along
    /// the *x* axis and putting the b vector in the *xy* plane. This make the
    /// matrix an upper triangular matrix:
    ///
    /// ```text
    /// | a_x   b_x   c_x |
    /// |  0    b_y   c_y |
    /// |  0     0    c_z |
    /// ```
    ///
    /// # Example
    /// ```
    /// # use chemfiles::UnitCell;
    /// let cell = UnitCell::new([10.0, 20.0, 30.0]);
    ///
    /// let matrix = cell.matrix();
    ///
    /// assert_eq!(matrix[0][0], 10.0);
    /// assert_eq!(matrix[1][1], 20.0);
    /// assert_eq!(matrix[2][2], 30.0);
    ///
    /// assert!(matrix[1][2].abs() < 1e-9);
    /// ```
    pub fn matrix(&self) -> [[f64; 3]; 3] {
        let mut matrix = [[0.0; 3]; 3];
        unsafe {
            check_success(chfl_cell_matrix(self.as_ptr(), matrix.as_mut_ptr()));
        }
        return matrix;
    }

    /// Get the shape of the unit cell.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{UnitCell, CellShape};
    /// let cell = UnitCell::new([10.0, 20.0, 30.0]);
    /// assert_eq!(cell.shape(), CellShape::Orthorhombic);
    /// ```
    pub fn shape(&self) -> CellShape {
        let mut shape = chfl_cellshape::CHFL_CELL_INFINITE;
        unsafe {
            check_success(chfl_cell_shape(self.as_ptr(), &mut shape));
        }
        return CellShape::from(shape);
    }

    /// Set the shape of the unit cell to `shape`.
    ///
    /// # Errors
    ///
    /// This can fail if the cell length or angles are incompatible with the
    /// new shape.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{UnitCell, CellShape};
    /// let mut cell = UnitCell::new([10.0, 20.0, 30.0]);
    /// assert_eq!(cell.shape(), CellShape::Orthorhombic);
    ///
    /// cell.set_shape(CellShape::Triclinic).unwrap();
    /// assert_eq!(cell.shape(), CellShape::Triclinic);
    /// ```
    pub fn set_shape(&mut self, shape: CellShape) -> Result<(), Error> {
        unsafe { check(chfl_cell_set_shape(self.as_mut_ptr(), shape.into())) }
    }

    /// Get the volume of the unit cell.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::UnitCell;
    /// let cell = UnitCell::new([10.0, 20.0, 30.0]);
    /// assert_eq!(cell.volume(), 10.0 * 20.0 * 30.0);
    /// ```
    pub fn volume(&self) -> f64 {
        let mut volume = 0.0;
        unsafe {
            check_success(chfl_cell_volume(self.as_ptr(), &mut volume));
        }
        return volume;
    }

    /// Wrap a `vector` in this unit cell.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::UnitCell;
    /// let cell = UnitCell::new([10.0, 20.0, 30.0]);
    ///
    /// let mut vector = [12.0, 5.2, -45.3];
    /// cell.wrap(&mut vector);
    /// assert_eq!(vector, [2.0, 5.2, 14.700000000000003]);
    /// ```
    pub fn wrap(&self, vector: &mut [f64; 3]) {
        unsafe {
            check_success(chfl_cell_wrap(self.as_ptr(), vector.as_mut_ptr()));
        }
    }
}

impl Drop for UnitCell {
    fn drop(&mut self) {
        unsafe {
            let _ = chfl_free(self.as_ptr().cast());
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn clone() {
        let mut cell = UnitCell::new([2.0, 3.0, 4.0]);
        assert_eq!(cell.lengths(), [2.0, 3.0, 4.0]);

        let copy = cell.clone();
        assert_eq!(copy.lengths(), [2.0, 3.0, 4.0]);

        cell.set_lengths([10.0, 12.0, 11.0]).unwrap();
        assert_eq!(cell.lengths(), [10.0, 12.0, 11.0]);
        assert_eq!(copy.lengths(), [2.0, 3.0, 4.0]);
    }

    #[test]
    fn lengths() {
        let mut cell = UnitCell::new([2.0, 3.0, 4.0]);
        assert_eq!(cell.lengths(), [2.0, 3.0, 4.0]);
        cell.set_lengths([10.0, 12.0, 11.0]).unwrap();
        assert_eq!(cell.lengths(), [10.0, 12.0, 11.0]);
    }

    #[test]
    fn angles() {
        let mut cell = UnitCell::new([2.0, 3.0, 4.0]);
        crate::assert_vector3d_eq(&cell.angles(), &[90.0, 90.0, 90.0], 1e-6);

        cell.set_shape(CellShape::Triclinic).unwrap();
        cell.set_angles([80.0, 89.0, 100.0]).unwrap();

        crate::assert_vector3d_eq(&cell.angles(), &[80.0, 89.0, 100.0], 1e-6);

        let cell = UnitCell::triclinic([1., 2., 3.], [80., 90., 100.]);
        crate::assert_vector3d_eq(&cell.angles(), &[80.0, 90.0, 100.0], 1e-6);
    }

    #[test]
    fn volume() {
        let cell = UnitCell::new([2.0, 3.0, 4.0]);
        assert_eq!(cell.volume(), 2.0 * 3.0 * 4.0);
    }

    #[test]
    fn wrap() {
        let cell = UnitCell::new([10.0, 20.0, 30.0]);
        let mut vector = [12.0, 5.2, -45.3];
        cell.wrap(&mut vector);
        crate::assert_vector3d_eq(&vector, &[2.0, 5.2, 14.7], 1e-6);
    }

    #[test]
    fn matrix() {
        let cell = UnitCell::new([2.0, 3.0, 4.0]);

        let matrix = cell.matrix();
        let result = [[2.0, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.0, 4.0]];

        for i in 0..3 {
            for j in 0..3 {
                approx::assert_ulps_eq!(matrix[i][j], result[i][j], epsilon = 1e-12);
            }
        }
    }

    #[test]
    fn from_matrix() {
        let cell = UnitCell::from_matrix([[10.0, 0.0, 0.0], [0.0, 21.0, 0.0], [0.0, 0.0, 32.0]]);
        assert_eq!(cell.shape(), CellShape::Orthorhombic);
        assert_eq!(cell.lengths(), [10.0, 21.0, 32.0]);

        let result_matrix = [[123.0, 4.08386, 71.7295], [0.0, 233.964, 133.571], [0.0, 0.0, 309.901]];
        let cell = UnitCell::from_matrix(result_matrix);

        assert_eq!(cell.shape(), CellShape::Triclinic);
        for i in 0..3 {
            approx::assert_ulps_eq!(cell.lengths()[i], [123.0, 234.0, 345.0][i], epsilon = 1e-3);
            approx::assert_ulps_eq!(cell.angles()[i], [67.0, 78.0, 89.0][i], epsilon = 1e-3);
        }

        let matrix = cell.matrix();
        for i in 0..3 {
            for j in 0..3 {
                approx::assert_ulps_eq!(matrix[i][j], result_matrix[i][j], epsilon = 1e-12);
            }
        }
    }

    #[test]
    fn shape() {
        let cell = UnitCell::new([2.0, 3.0, 4.0]);
        assert_eq!(cell.shape(), CellShape::Orthorhombic);

        let cell = UnitCell::infinite();
        assert_eq!(cell.shape(), CellShape::Infinite);

        let cell = UnitCell::triclinic([1.0, 2.0, 3.0], [80.0, 90.0, 100.0]);
        assert_eq!(cell.shape(), CellShape::Triclinic);

        let mut cell = UnitCell::new([10.0, 10.0, 10.0]);
        assert_eq!(cell.shape(), CellShape::Orthorhombic);
        cell.set_shape(CellShape::Triclinic).unwrap();
        assert_eq!(cell.shape(), CellShape::Triclinic);
    }
}