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
//! Contains the basic structures of an atomic system.
//!
//! A final system consists of a set of `Component`s. Each `Component`
//! in turn consists of a collection of `Residue`s, which
//! can be moved around and translated with ease. Each `Residue`
//! consists of some `Atom`s. These atoms have positions
//! relative to their parent.
//!
//! This somewhat convoluted structure is inherited from molecular
//! simulation packages in which atoms are commonly grouped as such.
//! A proper physical way to look at is that atoms can be
//! similarly grouped into molecules.

use coord::Coord;
use describe::{describe_list, Describe};
use database::{ComponentEntry, DataBase};
use iterator::AtomIterItem;

use colored::*;
use std::path::PathBuf;

/// Main structure of a constructed system with several components.
pub struct System {
    /// Title of system.
    pub title: String,
    /// Path to which the system will be written.
    pub output_path: PathBuf,
    /// Database with component and residue definitions.
    pub database: DataBase,
    /// List of constructed components.
    pub components: Vec<ComponentEntry>,
}

impl<'a> System {
    /// Calculate the total box size of the system as the maximum size along each axis
    /// from all components.
    pub fn box_size(&self) -> Coord {
        self.components
            .iter()
            .map(|object| object.box_size())
            .fold(Coord::new(0.0, 0.0, 0.0), |max_size, current| {
                Coord {
                    x: max_size.x.max(current.x),
                    y: max_size.y.max(current.y),
                    z: max_size.z.max(current.z),
                }
            })
    }

    /// Print the system state to standard error.
    pub fn print_state(&self) {
        eprintln!("{}", "System".underline().color("yellow"));
        eprintln!("Title       '{}'", self.title);
        eprintln!("Output path  {}", self.output_path.to_str().unwrap_or("(Not set)"));
        eprintln!("Box size     {}", self.box_size());
        eprintln!("");

        if self.components.len() > 0 {
            eprintln!("{}", describe_list("Components", &self.components));
        } else {
            eprintln!("(no constructed components)\n");
        }
    }

    /// Return an `Iterator` over all atoms in the whole system as `CurrentAtom` objects.
    ///
    /// Corrects residue and atom index numbers to be system-absolute instead
    /// of for each component.
    pub fn iter_atoms(&'a self) -> AtomIterItem {
        // We want to return system-wide atom and residue indices. The atom index
        // is easy to increase by one for each iterated atom, but to update the residue
        // index we have to see if it has changed from the previous iteration.
        struct Indices { atom: u64, residue: u64, last_residue: u64 }

        Box::new(self.components
            .iter()
            .flat_map(|object| object.iter_atoms())
            .scan(Indices { atom: 0, residue: 0, last_residue: 0 }, |state, mut current| {
                // Find out if the component residue number has increased, if so update it
                if current.residue_index != state.last_residue {
                    state.last_residue = current.residue_index;
                    state.residue += 1;
                }

                // Set the absolute atom and residue indices to the object
                current.atom_index = state.atom;
                current.residue_index = state.residue;

                state.atom += 1;

                Some(current)
            })
        )
    }

    /// Calculate the total number of atoms in the system.
    pub fn num_atoms(&self) -> u64 {
        self.components.iter().map(|object| object.num_atoms()).sum()
    }
}

/// Methods for yielding atoms and output information from constructed objects.
pub trait Component<'a> {
    /// Return the size of the object's bounding box seen from origo.
    ///
    /// That is, for a component of size (1, 1, 1) with origin (1, 1, 1)
    /// this returns (2, 2, 2).
    fn box_size(&self) -> Coord;

    /// Return an `Iterator` over all atoms in the object as `CurrentAtom` objects.
    fn iter_atoms(&'a self) -> AtomIterItem<'a>;

    /// Return the number of atoms in the object.
    fn num_atoms(&self) -> u64;

    /// Return the component with its coordinates adjusted to lie within its box.
    fn with_pbc(self) -> Self;
}

#[macro_export]
/// Macro to implement `Component` for an object.
///
/// The object has to contain the fields
/// ```
/// {
///     residue: Option<Residue>,
///     origin: Coord,
///     coords: [Coord]
/// }
/// ```
/// and the method `calc_box_size`.
macro_rules! impl_component {
    ( $( $class:path ),+ ) => {
        $(
            impl<'a> Component<'a> for $class {
                fn box_size(&self) -> Coord {
                    self.calc_box_size() + self.origin
                }

                fn iter_atoms(&self) -> AtomIterItem {
                    Box::new(
                        AtomIterator::new(self.residue.as_ref(), &self.coords, self.origin)
                    )
                }

                fn num_atoms(&self) -> u64 {
                    let residue_len = self.residue
                        .as_ref()
                        .map(|res| res.atoms.len())
                        .unwrap_or(0);

                    (residue_len * self.coords.len()) as u64
                }

                fn with_pbc(mut self) -> Self {
                    let box_size = self.calc_box_size();

                    self.coords
                        .iter_mut()
                        .for_each(|c| *c = c.with_pbc(box_size));

                    self
                }
            }
        )*
    }
}

#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
/// Every atom in a residue has their own code and relative
/// position some base coordinate.
pub struct Atom {
    /// Atom code.
    pub code: String,
    /// Relative position.
    pub position: Coord,
}

impl Describe for Atom {
    fn describe(&self) -> String {
        format!("{} {}", self.code, self.position)
    }

    fn describe_short(&self) -> String {
        format!("{}", self.code)
    }
}

/// A base for generating atoms belonging to a residue.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Residue {
    pub code: String,
    pub atoms: Vec<Atom>,
}

impl Describe for Residue {
    fn describe(&self) -> String {
        format!("{} ({} atoms)", self.code, self.atoms.len())
    }

    fn describe_short(&self) -> String {
        format!("{}", self.code)
    }
}

#[macro_export]
/// Construct a Residue with a code and atoms.
///
/// At least one atom has to be present in the base. This is not a limitation
/// when explicitly constructing a residue, but it makes no sense to allow
/// it when invoking a constructor like this.
///
/// # Examples
/// ```
/// # #[macro_use] extern crate grafen;
/// # use grafen::coord::Coord;
/// # use grafen::system::{Atom, Residue};
/// # fn main() {
/// let expect = Residue {
///     code: "RES".to_string(),
///     atoms: vec![
///         Atom { code: "A".to_string(), position: Coord::new(0.0, 0.0, 0.0) },
///         Atom { code: "B".to_string(), position: Coord::new(1.0, 2.0, 3.0) }
///     ],
/// };
///
/// let residue = resbase![
///     "RES",
///     ("A", 0.0, 0.0, 0.0),
///     ("B", 1.0, 2.0, 3.0)
/// ];
///
/// assert_eq!(expect, residue);
/// # }
/// ```
macro_rules! resbase {
    (
        $rescode:expr,
        $(($atname:expr, $x:expr, $y:expr, $z:expr)),+
    ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push(
                    Atom {
                        code: $atname.to_string(),
                        position: Coord::new($x, $y, $z),
                    }
                );
            )*

            Residue {
                code: $rescode.to_string(),
                atoms: temp_vec,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use coord::Translate;
    use iterator::AtomIterator;
    use volume::Cuboid;

    #[test]
    fn create_residue_base_macro() {
        let expect = Residue {
            code: "RES".to_string(),
            atoms: vec![
                Atom { code: "A1".to_string(), position: Coord::new(0.0, 0.0, 0.0) },
                Atom { code: "A2".to_string(), position: Coord::new(0.0, 1.0, 2.0) }
            ],
        };
        let result = resbase![
            "RES",
            ("A1", 0.0, 0.0, 0.0),
            ("A2", 0.0, 1.0, 2.0)
        ];

        assert_eq!(expect, result);
    }

    // Verify that the macro generated `iter_atoms` methods work as expected.

    #[derive(Debug, Deserialize, Serialize)]
    struct TestObject { residue: Option<Residue>, origin: Coord, coords: Vec<Coord> }
    impl Describe for TestObject {
        fn describe(&self) -> String { unimplemented!(); }
        fn describe_short(&self) -> String { unimplemented!(); }
    }
    impl TestObject { fn calc_box_size(&self) -> Coord { unimplemented!(); } }

    impl_translate![TestObject];
    impl_component![TestObject];

    #[test]
    fn iterate_over_atoms_in_macro_generated_impl_object() {
        let residue = resbase!["RES", ("A", 0.0, 0.1, 0.2), ("B", 0.3, 0.4, 0.5)];
        let constructed = TestObject {
            residue: Some(residue.clone()),
            origin: Coord::ORIGO,
            coords: vec![Coord::new(0.0, 2.0, 4.0), Coord::new(1.0, 3.0, 5.0)],
        };

        // Skip to and compare against the last atom
        let mut iter = constructed.iter_atoms().skip(3);

        let atom = iter.next().unwrap();
        assert_eq!(3, atom.atom_index);
        assert_eq!(1, atom.residue_index);
        assert_eq!(&residue.atoms[1], atom.atom);
        assert_eq!(&residue, atom.residue);
        assert_eq!(residue.atoms[1].position + constructed.coords[1], atom.position);

        assert_eq!(None, iter.next());
    }

    #[test]
    fn num_atoms_in_macro_generated_impl_objects() {
        // An object with 2 residues * 2 atoms / residue = 4 atoms
        let residue = resbase!["RES", ("A", 0.0, 0.1, 0.2), ("B", 0.3, 0.4, 0.5)];
        let mut constructed = TestObject {
            residue: Some(residue.clone()),
            origin: Coord::ORIGO,
            coords: vec![Coord::new(0.0, 2.0, 4.0), Coord::new(1.0, 3.0, 5.0)],
        };

        assert_eq!(4, constructed.num_atoms());

        // With no residue set, no atoms
        constructed.residue = None;
        assert_eq!(0, constructed.num_atoms());
    }

    #[test]
    fn box_size_in_macro_generated_impls_adds_origin() {
        let origin = Coord::new(0.0, 1.0, 2.0);
        let size = Coord::new(5.0, 6.0, 7.0);

        let cuboid = Cuboid {
            name: None,
            residue: None,
            size,
            origin,
            density: None,
            coords: vec![],
        };

        assert_eq!(origin + size, cuboid.box_size());
    }

    #[test]
    fn with_pbc_in_macro_generated_impls_works_locally() {
        let origin = Coord::new(10.0, 20.0, 30.0);
        let size = Coord::new(1.0, 2.0, 3.0);

        let cuboid = Cuboid {
            origin,
            size,
            coords: vec![
                Coord::new(-0.9, 0.1, 0.1), // outside locally
                Coord::new(0.1, 0.1, 0.1),  // inside locally
                Coord::new(1.1, 0.1, 0.1),  // outside locally
            ],
            .. Cuboid::default()
        }.with_pbc();

        let expected = vec![
            Coord::new(0.1, 0.1, 0.1), // moved inside
            Coord::new(0.1, 0.1, 0.1), // unmoved
            Coord::new(0.1, 0.1, 0.1), // moved inside
        ];

        assert_eq!(cuboid.coords, expected);
    }

    #[test]
    fn iterate_over_atoms_in_macro_generated_impl_without_residue_returns_empty_iterator() {
        let constructed = TestObject {
            residue: None,
            origin: Coord::ORIGO,
            coords: vec![Coord::new(0.0, 2.0, 4.0), Coord::new(1.0, 3.0, 5.0)],
        };

        let mut iter = constructed.iter_atoms();
        assert_eq!(None, iter.next());
    }

    #[test]
    fn iterate_over_atoms_in_whole_system_gives_correct_results() {
        // The first component has 3 residues * 2 atoms / residue = 6 atoms
        let residue1 = resbase!["ONE", ("A", 1.0, 1.0, 1.0), ("B", 2.0, 2.0, 2.0)];
        let component1 = Cuboid {
            name: None,
            residue: Some(residue1.clone()),
            origin: Coord::default(),
            size: Coord::default(),
            density: None,
            coords: vec![Coord::default(), Coord::default(), Coord::default()],
        };

        let origin = Coord::new(10.0, 20.0, 30.0);
        let position = Coord::new(1.0, 2.0, 3.0);

        // The second component has 2 residues * 1 atom / residue = 2 atoms
        let residue2 = resbase!["TWO", ("C", 5.0, 6.0, 7.0)];
        let component2 = Cuboid {
            name: None,
            residue: Some(residue2.clone()),
            origin: origin,
            size: Coord::default(),
            density: None,
            coords: vec![position, Coord::default()],
        };

        let system = System {
            title: String::new(),
            output_path: PathBuf::new(),
            database: DataBase::new(),
            components: vec![
                ComponentEntry::VolumeCuboid(component1),
                ComponentEntry::VolumeCuboid(component2)
            ],
        };

        let iter = system.iter_atoms();

        // Inspect the seventh atom: the first in the second component
        let atom = iter.skip(6).next().unwrap();

        assert_eq!(6, atom.atom_index);
        assert_eq!(3, atom.residue_index);
        assert_eq!(&residue2.atoms[0], atom.atom);
        assert_eq!(&residue2, atom.residue);
        assert_eq!(origin + position + residue2.atoms[0].position, atom.position);
    }

    #[test]
    fn num_atoms_in_system() {
        // 2 components * 3 residues / component * 2 atoms / residue = 12 atoms
        let residue = resbase!["RES", ("A", 0.0, 0.0, 0.0), ("B", 1.0, 0.0, 0.0)];
        let component = ComponentEntry::VolumeCuboid(Cuboid {
            name: None,
            residue: Some(residue.clone()),
            origin: Coord::default(),
            size: Coord::default(),
            density: None,
            coords: vec![Coord::default(), Coord::default(), Coord::default()],
        });

        let system = System {
            title: String::new(),
            output_path: PathBuf::new(),
            database: DataBase::new(),
            components: vec![
                component.clone(), component.clone()],
        };

        assert_eq!(12, system.num_atoms());
    }

    #[test]
    fn box_size_of_system_adds_origin() {
        let component1 = ComponentEntry::VolumeCuboid(Cuboid {
            name: None,
            residue: None,
            origin: Coord::new(0.0, 0.0, 0.0),
            size: Coord::new(5.0, 5.0, 5.0),
            density: None,
            coords: vec![],
        });

        let component2 = ComponentEntry::VolumeCuboid(Cuboid {
            name: None,
            residue: None,
            origin: Coord::new(3.0, 3.0, 3.0),
            size: Coord::new(3.0, 2.0, 1.0),
            density: None,
            coords: vec![],
        });

        let system = System {
            title: String::new(),
            output_path: PathBuf::new(),
            database: DataBase::new(),
            components: vec![
                component1.clone(),
                component2.clone()
            ],
        };

        assert_eq!(Coord::new(6.0, 5.0, 5.0), system.box_size());
    }
}