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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
// Chemfiles, a modern library for chemistry file reading and writing
// Copyright (C) 2015-2017 Guillaume Fraux
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
use std::ops::Drop;
use std::ptr;
use std::slice;

use chemfiles_sys::*;
use errors::{check, Error};
use {Atom, Topology, UnitCell};
use Result;

/// A `Frame` contains data from one simulation step: the current unit
/// cell, the topology, the positions, and the velocities of the particles in
/// the system. If some information is missing (topology or velocity or unit
/// cell), the corresponding data is filled with a default value.
pub struct Frame {
    handle: *const CHFL_FRAME
}

impl Clone for Frame {
    fn clone(&self) -> Frame {
        unsafe {
            let new_handle = chfl_frame_copy(self.as_ptr());
            Frame::from_ptr(new_handle).expect(
                "Out of memory when copying a Frame"
            )
        }
    }
}

impl Frame {
    /// Create a `Frame` from a C pointer.
    ///
    /// This function is unsafe because no validity check is made on the pointer,
    /// except for it being non-null.
    #[inline]
    #[doc(hidden)]
    pub unsafe fn from_ptr(ptr: *const CHFL_FRAME) -> Result<Frame> {
        if ptr.is_null() {
            Err(Error::null_ptr())
        } else {
            Ok(Frame{handle: ptr})
        }
    }

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

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

    /// Create an empty frame. It will be resized by the library as needed.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::Frame;
    /// let frame = Frame::new().unwrap();
    /// ```
    pub fn new() -> Result<Frame> {
        let handle: *const CHFL_FRAME;
        unsafe {
            handle = chfl_frame();
        }

        if handle.is_null() {
            Err(Error::null_ptr())
        } else {
            Ok(Frame{handle: handle})
        }
    }

    /// Get a copy of the atom at index `index` in this frame.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{Frame, Atom};
    /// let mut frame = Frame::new().unwrap();
    /// frame.add_atom(&Atom::new("Zn").unwrap(), (0.0, 0.0, 0.0), None).unwrap();
    ///
    /// let atom = frame.atom(0).unwrap();
    /// assert_eq!(atom.name(), Ok(String::from("Zn")));
    /// ```
    pub fn atom(&self, index: u64) -> Result<Atom> {
        unsafe {
            let handle = chfl_atom_from_frame(self.as_ptr(), index);
            Atom::from_ptr(handle)
        }
    }

    /// Get the current number of atoms in this frame.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{Frame, Atom};
    /// let mut frame = Frame::new().unwrap();
    /// assert_eq!(frame.natoms(), Ok(0));
    ///
    /// frame.resize(67).unwrap();
    /// assert_eq!(frame.natoms(), Ok(67));
    /// ```
    pub fn natoms(&self) -> Result<u64> {
        let mut natoms = 0;
        unsafe {
            try!(check(chfl_frame_atoms_count(self.as_ptr(), &mut natoms)));
        }
        return Ok(natoms);
    }

    /// Resize the positions and the velocities in this frame, to make space for
    /// `natoms` atoms. Previous data is conserved, as well as the presence of
    /// absence of velocities.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{Frame, Atom};
    /// let mut frame = Frame::new().unwrap();
    /// frame.resize(67).unwrap();
    /// assert_eq!(frame.natoms(), Ok(67));
    /// ```
    pub fn resize(&mut self, natoms: u64) -> Result<()> {
        unsafe {
            try!(check(chfl_frame_resize(self.as_mut_ptr(), natoms)));
        }
        return Ok(());
    }

    /// Add an `Atom` and the corresponding position and optionally velocity
    /// data to this frame.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{Frame, Atom};
    /// let mut frame = Frame::new().unwrap();
    /// frame.add_atom(&Atom::new("Zn").unwrap(), (1.0, 1.0, 2.0), None).unwrap();
    ///
    /// frame.add_velocities().unwrap();
    /// frame.add_atom(&Atom::new("Zn").unwrap(), (-1.0, 1.0, 2.0), (0.2, 0.1, 0.0)).unwrap();
    /// ```
    pub fn add_atom<V>(&mut self, atom: &Atom, position: (f64, f64, f64), velocity: V) -> Result<()>
        where V: Into<Option<(f64, f64, f64)>> {
        let position = [position.0, position.1, position.2];
        let velocity_data;
        let velocity_ptr = match velocity.into() {
            Some((x, y, z)) => {
                velocity_data = [x, y, z];
                velocity_data.as_ptr()
            }
            None => 0 as *const _
        };

        unsafe {
            try!(check(chfl_frame_add_atom(
                self.as_mut_ptr(),
                atom.as_ptr(),
                position.as_ptr(),
                velocity_ptr
            )));
        }

        return Ok(());
    }

    /// Get a view into the positions of this frame.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::Frame;
    /// let mut frame = Frame::new().unwrap();
    /// frame.resize(67).unwrap();
    ///
    /// let positions = frame.positions().unwrap();
    /// assert_eq!(positions.len(), 67);
    /// assert_eq!(positions[0], [0.0, 0.0, 0.0]);
    /// ```
    pub fn positions(&self) -> Result<&[[f64; 3]]> {
        let mut ptr = ptr::null_mut();
        let mut natoms = 0;
        unsafe {
            try!(check(chfl_frame_positions(
                // not using .as_ptr() because the C function uses a *mut
                // pointer and we are re-creating the shared/mut by ourselve
                self.handle as *mut CHFL_FRAME,
                &mut ptr,
                &mut natoms
            )));
        }
        let res = unsafe {
            #[allow(cast_possible_truncation)]
            slice::from_raw_parts(ptr, natoms as usize)
        };
        return Ok(res);
    }

    /// Get a mutable view into the positions of this frame.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::Frame;
    /// let mut frame = Frame::new().unwrap();
    /// frame.resize(67).unwrap();
    /// {
    ///     let positions = frame.positions_mut().unwrap();
    ///     assert_eq!(positions[0], [0.0, 0.0, 0.0]);
    ///     positions[0] = [1.0, 2.0, 3.0];
    /// }
    ///
    /// let positions = frame.positions().unwrap();
    /// assert_eq!(positions[0], [1.0, 2.0, 3.0]);
    /// ```
    pub fn positions_mut(&mut self) -> Result<&mut [[f64; 3]]> {
        let mut ptr = ptr::null_mut();
        let mut natoms = 0;
        unsafe {
            try!(check(chfl_frame_positions(
                self.as_mut_ptr(),
                &mut ptr,
                &mut natoms
            )));
        }
        let res = unsafe {
            #[allow(cast_possible_truncation)]
            slice::from_raw_parts_mut(ptr, natoms as usize)
        };
        return Ok(res);
    }

    /// Get a view into the velocities of this frame.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::Frame;
    /// let mut frame = Frame::new().unwrap();
    /// frame.resize(67).unwrap();
    /// frame.add_velocities().unwrap();
    ///
    /// let velocities = frame.velocities().unwrap();
    /// assert_eq!(velocities.len(), 67);
    /// assert_eq!(velocities[0], [0.0, 0.0, 0.0]);
    /// ```
    pub fn velocities(&self) -> Result<&[[f64; 3]]> {
        let mut ptr = ptr::null_mut();
        let mut natoms = 0;
        unsafe {
            try!(check(chfl_frame_velocities(
                // not using .as_ptr() because the C function uses a *mut
                // pointer and we are re-creating the shared/mut by ourselve
                self.handle as *mut CHFL_FRAME,
                &mut ptr,
                &mut natoms
            )));
        }
        let res = unsafe {
            #[allow(cast_possible_truncation)]
            slice::from_raw_parts(ptr, natoms as usize)
        };
        return Ok(res);
    }

    /// Get a mutable view into the velocities of this frame.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::Frame;
    /// let mut frame = Frame::new().unwrap();
    /// frame.resize(67).unwrap();
    /// frame.add_velocities().unwrap();
    /// {
    ///     let velocities = frame.velocities_mut().unwrap();
    ///     assert_eq!(velocities[0], [0.0, 0.0, 0.0]);
    ///     velocities[0] = [1.0, 2.0, 3.0];
    /// }
    ///
    /// let velocities = frame.velocities().unwrap();
    /// assert_eq!(velocities[0], [1.0, 2.0, 3.0]);
    /// ```
    pub fn velocities_mut(&mut self) -> Result<&mut [[f64; 3]]> {
        let mut ptr = ptr::null_mut();
        let mut natoms = 0;
        unsafe {
            try!(check(chfl_frame_velocities(
                self.as_mut_ptr(),
                &mut ptr,
                &mut natoms
            )));
        }
        let res = unsafe {
            #[allow(cast_possible_truncation)]
            slice::from_raw_parts_mut(ptr, natoms as usize)
        };
        return Ok(res);
    }

    /// Check if this frame contains velocity data.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::Frame;
    /// let mut frame = Frame::new().unwrap();
    /// assert_eq!(frame.has_velocities(), Ok(false));
    ///
    /// frame.add_velocities().unwrap();
    /// assert_eq!(frame.has_velocities(), Ok(true));
    /// ```
    pub fn has_velocities(&self) -> Result<bool> {
        let mut res = 0;
        unsafe {
            try!(check(chfl_frame_has_velocities(self.as_ptr(), &mut res)));
        }
        return Ok(res != 0);
    }

    /// Add velocity data to this frame. If the frame already have velocities,
    /// this does nothing.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::Frame;
    /// let mut frame = Frame::new().unwrap();
    /// assert_eq!(frame.has_velocities(), Ok(false));
    ///
    /// frame.add_velocities().unwrap();
    /// assert_eq!(frame.has_velocities(), Ok(true));
    /// ```
    pub fn add_velocities(&mut self) -> Result<()> {
        unsafe {
            try!(check(chfl_frame_add_velocities(self.as_mut_ptr())));
        }
        return Ok(());
    }

    /// Get a copy of the `UnitCell` from this frame.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{Frame, CellShape};
    /// let frame = Frame::new().unwrap();
    ///
    /// let cell = frame.cell().unwrap();
    /// assert_eq!(cell.shape(), Ok(CellShape::Infinite));
    /// ```
    pub fn cell(&self) -> Result<UnitCell> {
        unsafe {
            let handle = chfl_cell_from_frame(self.as_ptr());
            UnitCell::from_ptr(handle)
        }
    }

    /// Set the `UnitCell` of this frame to `cell`.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{Frame, UnitCell, CellShape};
    /// let mut frame = Frame::new().unwrap();
    ///
    /// frame.set_cell(&UnitCell::new(10.0, 10.0, 10.0).unwrap()).unwrap();
    ///
    /// let cell = frame.cell().unwrap();
    /// assert_eq!(cell.shape(), Ok(CellShape::Orthorhombic));
    /// assert_eq!(cell.lengths(), Ok((10.0, 10.0, 10.0)));
    /// ```
    pub fn set_cell(&mut self, cell: &UnitCell) -> Result<()> {
        unsafe {
            try!(check(chfl_frame_set_cell(
                self.as_mut_ptr(),
                cell.as_ptr()
            )));
        }
        return Ok(());
    }

    /// Get a copy of the `Topology` from this frame.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::Frame;
    /// let mut frame = Frame::new().unwrap();
    /// frame.resize(42).unwrap();
    ///
    /// let topology = frame.topology().unwrap();
    /// assert_eq!(topology.natoms(), Ok(42));
    /// ```
    pub fn topology(&self) -> Result<Topology> {
        unsafe {
            let handle = chfl_topology_from_frame(self.as_ptr());
            Topology::from_ptr(handle)
        }
    }

    /// Set the `Topology` of this frame to `topology`. The topology must
    /// contain the same number of atoms that this frame.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{Frame, Topology, Atom};
    /// let mut frame = Frame::new().unwrap();
    /// frame.resize(2).unwrap();
    ///
    /// let mut topology = Topology::new().unwrap();
    /// topology.add_atom(&Atom::new("Cl").unwrap()).unwrap();
    /// topology.add_atom(&Atom::new("Cl").unwrap()).unwrap();
    /// topology.add_bond(0, 1);
    ///
    /// frame.set_topology(&topology);
    /// assert_eq!(frame.atom(0).unwrap().name(), Ok(String::from("Cl")));
    /// ```
    pub fn set_topology(&mut self, topology: &Topology) -> Result<()> {
        unsafe {
            try!(check(chfl_frame_set_topology(
                self.as_mut_ptr(),
                topology.as_ptr()
            )));
        }
        return Ok(());
    }

    /// Get this frame step, i.e. the frame number in the trajectory
    ///
    /// # Example
    /// ```
    /// # use chemfiles::Frame;
    /// let frame = Frame::new().unwrap();
    /// assert_eq!(frame.step(), Ok(0));
    /// ```
    pub fn step(&self) -> Result<u64> {
        let mut res = 0;
        unsafe {
            try!(check(chfl_frame_step(self.as_ptr(), &mut res)));
        }
        return Ok(res);
    }

    /// Set this frame step to `step`.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::Frame;
    /// let mut frame = Frame::new().unwrap();
    /// assert_eq!(frame.step(), Ok(0));
    ///
    /// frame.set_step(10).unwrap();
    /// assert_eq!(frame.step(), Ok(10));
    /// ```
    pub fn set_step(&mut self, step: u64) -> Result<()> {
        unsafe {
            try!(check(chfl_frame_set_step(self.as_mut_ptr(), step)));
        }
        return Ok(());
    }

    /// Guess the bonds, angles and dihedrals in this `frame`.
    ///
    /// The bonds are guessed using a distance-based algorithm, and then angles
    /// and dihedrals are guessed from the bonds.
    ///
    /// # Example
    /// ```
    /// # use chemfiles::{Frame, Atom};
    /// let mut frame = Frame::new().unwrap();
    ///
    /// frame.add_atom(&Atom::new("Cl").unwrap(), (0.0, 0.0, 0.0), None).unwrap();
    /// frame.add_atom(&Atom::new("Cl").unwrap(), (1.5, 0.0, 0.0), None).unwrap();
    /// assert_eq!(frame.topology().unwrap().bonds_count(), Ok(0));
    ///
    /// frame.guess_topology().unwrap();
    /// assert_eq!(frame.topology().unwrap().bonds_count(), Ok(1));
    /// ```
    pub fn guess_topology(&mut self) -> Result<()> {
        unsafe {
            try!(check(chfl_frame_guess_topology(self.as_mut_ptr())));
        }
        return Ok(());
    }
}

impl Drop for Frame {
    fn drop(&mut self) {
        unsafe {
            let status = chfl_frame_free(self.as_mut_ptr());
            debug_assert_eq!(status, chfl_status::CHFL_SUCCESS);
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use ::{Atom, Topology, UnitCell};

    #[test]
    fn clone() {
        let mut frame = Frame::new().unwrap();
        assert_eq!(frame.natoms(), Ok(0));
        let copy = frame.clone();
        assert_eq!(copy.natoms(), Ok(0));

        frame.resize(42).unwrap();
        assert_eq!(frame.natoms(), Ok(42));
        assert_eq!(copy.natoms(), Ok(0));
    }

    #[test]
    fn size() {
        let mut frame = Frame::new().unwrap();
        assert_eq!(frame.natoms(), Ok(0));

        frame.resize(12).unwrap();
        assert_eq!(frame.natoms(), Ok(12));
    }

    #[test]
    fn add_atom() {
        let atom = Atom::new("U").unwrap();
        let mut frame = Frame::new().unwrap();

        frame.add_atom(&atom, (1.0, 1.0, 2.0), None).unwrap();
        assert_eq!(frame.natoms(), Ok(1));
        assert_eq!(frame.atom(0).unwrap().name(), Ok("U".into()));

        let positions: &[[f64; 3]] = &[[1.0, 1.0, 2.0]];
        assert_eq!(frame.positions(), Ok(positions));

        frame.add_velocities().unwrap();

        let atom = Atom::new("F").unwrap();
        frame.add_atom(&atom, (1.0, 1.0, 2.0), (4.0, 3.0, 2.0)).unwrap();
        assert_eq!(frame.natoms(), Ok(2));
        assert_eq!(frame.atom(0).unwrap().name(), Ok("U".into()));
        assert_eq!(frame.atom(1).unwrap().name(), Ok("F".into()));

        let positions: &[[f64; 3]] = &[[1.0, 1.0, 2.0], [1.0, 1.0, 2.0]];
        assert_eq!(frame.positions(), Ok(positions));

        let velocities: &[[f64; 3]] = &[[0.0, 0.0, 0.0], [4.0, 3.0, 2.0]];
        assert_eq!(frame.velocities(), Ok(velocities));
    }

    #[test]
    fn positions() {
        let mut frame = Frame::new().unwrap();
        frame.resize(4).unwrap();
        let expected = [[1.0, 2.0, 3.0],
                        [4.0, 5.0, 6.0],
                        [7.0, 8.0, 9.0],
                        [10.0, 11.0, 12.0]];
        {
            let positions = frame.positions_mut().unwrap();
            positions.clone_from_slice(expected.as_ref());
        }

        assert_eq!(frame.positions(), Ok(expected.as_ref()));
    }

    #[test]
    fn velocities() {
        let mut frame = Frame::new().unwrap();
        frame.resize(4).unwrap();
        assert_eq!(frame.has_velocities(), Ok(false));
        frame.add_velocities().unwrap();
        assert_eq!(frame.has_velocities(), Ok(true));

        let expected = [[1.0, 2.0, 3.0],
                        [4.0, 5.0, 6.0],
                        [7.0, 8.0, 9.0],
                        [10.0, 11.0, 12.0]];

        {
            let velocities = frame.velocities_mut().unwrap();
            velocities.clone_from_slice(expected.as_ref());
        }

        assert_eq!(frame.velocities(), Ok(expected.as_ref()));
    }

    #[test]
    fn cell() {
        let mut frame = Frame::new().unwrap();
        let cell = UnitCell::new(3.0, 4.0, 5.0).unwrap();

        assert!(frame.set_cell(&cell).is_ok());
        let cell = frame.cell().unwrap();
        assert_eq!(cell.lengths(), Ok((3.0, 4.0, 5.0)));
    }

    #[test]
    fn topology() {
        let mut frame = Frame::new().unwrap();
        frame.resize(2).unwrap();
        let mut topology = Topology::new().unwrap();

        topology.add_atom(&Atom::new("Zn").unwrap()).unwrap();
        topology.add_atom(&Atom::new("Ar").unwrap()).unwrap();

        assert!(frame.set_topology(&topology).is_ok());

        let topology = frame.topology().unwrap();

        assert_eq!(topology.atom(0).unwrap().name(), Ok(String::from("Zn")));
        assert_eq!(topology.atom(1).unwrap().name(), Ok(String::from("Ar")));

        assert_eq!(frame.atom(0).unwrap().name(), Ok(String::from("Zn")));
        assert_eq!(frame.atom(1).unwrap().name(), Ok(String::from("Ar")));
    }

    #[test]
    fn step() {
        let mut frame = Frame::new().unwrap();
        assert_eq!(frame.step(), Ok(0));

        assert!(frame.set_step(42).is_ok());
        assert_eq!(frame.step(), Ok(42));
    }
}