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
#![allow(dead_code)]
use crate::reference_tables;
use crate::structs::*;
use crate::transformation::TransformationMatrix;
use doc_cfg::doc_cfg;
#[cfg(feature = "rayon")]
use rayon::prelude::*;
use std::cmp::Ordering;
use std::fmt;

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
/// A Conformer containing multiple atoms, analogous to `atom_group` in cctbx
pub struct Conformer {
    /// The name of this Conformer
    name: String,
    /// The alternative location of this Conformer, None is blank
    alternative_location: Option<String>,
    /// The list of atoms making up this Conformer
    atoms: Vec<Atom>,
    /// The modification, if present
    modification: Option<(String, String)>,
}

impl Conformer {
    /// Create a new Conformer
    ///
    /// ## Arguments
    /// * `name` - the name
    /// * `alt_loc` - the alternative location identifier, if not blank
    /// * `atom` - if available it can already add an atom
    ///
    /// ## Fails
    /// It fails and returns `None` if any of the characters making up the name are invalid.
    #[must_use]
    pub fn new(
        name: impl AsRef<str>,
        alt_loc: Option<&str>,
        atom: Option<Atom>,
    ) -> Option<Conformer> {
        prepare_identifier_uppercase(name).map(|n| {
            let mut res = Conformer {
                name: n,
                alternative_location: None,
                atoms: Vec::new(),
                modification: None,
            };
            if let Some(al) = alt_loc {
                res.alternative_location = prepare_identifier_uppercase(al);
            }
            if let Some(a) = atom {
                res.atoms.push(a);
            }
            res
        })
    }

    /// Get the name of the Conformer
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Set the name of the Conformer.
    ///
    /// ## Fails
    /// It fails if any of the characters of the new name are invalid.
    pub fn set_name(&mut self, new_name: impl AsRef<str>) -> bool {
        prepare_identifier_uppercase(new_name)
            .map(|n| self.name = n)
            .is_some()
    }

    /// Get the alternative location of the Conformer, if present.
    pub fn alternative_location(&self) -> Option<&str> {
        self.alternative_location.as_deref()
    }

    /// Set the alternative location of the Conformer.
    ///
    /// ## Fails
    /// It fails if any of the characters of the new alternative location are invalid.
    pub fn set_alternative_location(&mut self, new_loc: &str) -> bool {
        if let Some(l) = prepare_identifier_uppercase(new_loc) {
            self.alternative_location = Some(l);
            true
        } else {
            false
        }
    }

    /// Set the alternative location of the Conformer to `None`.
    pub fn remove_alternative_location(&mut self) {
        self.alternative_location = None;
    }

    /// Returns the uniquely identifying construct for this Conformer.
    /// It consists of the name and alternative location.
    pub fn id(&self) -> (&str, Option<&str>) {
        (&self.name, self.alternative_location())
    }

    /// Get the modification of this Conformer e.g., chemical or post-translational. These is saved in the MODRES records in the PDB file.
    pub const fn modification(&self) -> Option<&(String, String)> {
        self.modification.as_ref()
    }

    /// Set the modification of this Conformer e.g., chemical or post-translational. These will be saved in the MODRES records in the PDB file.
    /// # Errors
    /// It fails if the conformer name or comment has invalid characters.
    pub fn set_modification(&mut self, new_modification: (String, String)) -> Result<(), String> {
        if !valid_identifier(&new_modification.0) {
            Err(format!(
                "New modification has invalid characters for standard conformer name, conformer: {:?}, standard name \"{}\"",
                self.id(), new_modification.0
            ))
        } else if !valid_text(&new_modification.1) {
            Err(format!(
                "New modification has invalid characters in the comment, conformer: {:?}, comment \"{}\"",
                self.id(), new_modification.1
            ))
        } else {
            self.modification = Some(new_modification);
            Ok(())
        }
    }

    /// The number of atoms making up this Conformer
    pub fn atom_count(&self) -> usize {
        self.atoms.len()
    }

    /// Get a specific atom from the list of atoms making up this Conformer.
    ///
    /// ## Arguments
    /// * `index` - the index of the atom
    ///
    /// ## Fails
    /// It returns `None` if the index is out of bounds.
    pub fn atom(&self, index: usize) -> Option<&Atom> {
        self.atoms.get(index)
    }

    /// Get a specific atom as a mutable reference from list of atoms making up this Conformer.
    ///
    /// ## Arguments
    /// * `index` - the index of the atom
    ///
    /// ## Fails
    /// It returns `None` if the index is out of bounds.
    pub fn atom_mut(&mut self, index: usize) -> Option<&mut Atom> {
        self.atoms.get_mut(index)
    }

    /// Get a reference to the specified atom which is unique within a single conformer.
    /// The algorithm is based on binary search so it is faster than an exhaustive search, but the
    /// underlying vector is assumed to be sorted. This assumption can be enforced
    /// by using `conformer.sort()`.
    pub fn binary_find_atom(&self, serial_number: usize) -> Option<&Atom> {
        if let Ok(i) = self
            .atoms
            .binary_search_by(|a| a.serial_number().cmp(&serial_number))
        {
            unsafe { Some(self.atoms.get_unchecked(i)) }
        } else {
            None
        }
    }

    /// Get a mutable reference to the specified atom which is unique within a single conformer.
    /// The algorithm is based on binary search so it is faster than an exhaustive search, but the
    /// underlying vector is assumed to be sorted. This assumption can be enforced
    /// by using `conformer.sort()`.
    pub fn binary_find_atom_mut(&mut self, serial_number: usize) -> Option<&mut Atom> {
        if let Ok(i) = self
            .atoms
            .binary_search_by(|a| a.serial_number().cmp(&serial_number))
        {
            unsafe { Some(self.atoms.get_unchecked_mut(i)) }
        } else {
            None
        }
    }

    /// Find all atoms matching the given information
    pub fn find(&self, search: Search) -> impl DoubleEndedIterator<Item = &Atom> + '_ {
        self.atoms()
            .filter(move |a| search.add_atom_info(a).complete().unwrap_or(true))
    }

    /// Find all atoms matching the given information
    pub fn find_mut(&mut self, search: Search) -> impl DoubleEndedIterator<Item = &mut Atom> + '_ {
        self.atoms_mut()
            .filter(move |a| search.add_atom_info(a).complete().unwrap_or(true))
    }

    /// Get an iterator of references to Atoms making up this Conformer.
    /// Double ended so iterating from the end is just as fast as from the start.
    pub fn atoms(&self) -> impl DoubleEndedIterator<Item = &Atom> + '_ {
        self.atoms.iter()
    }

    /// Get a parallel iterator of references to Atoms making up this Conformer.
    #[doc_cfg(feature = "rayon")]
    pub fn par_atoms(&self) -> impl ParallelIterator<Item = &Atom> + '_ {
        self.atoms.par_iter()
    }

    /// Get an iterator of mutable references to Atoms making up this Conformer.
    /// Double ended so iterating from the end is just as fast as from the start.
    pub fn atoms_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Atom> + '_ {
        self.atoms.iter_mut()
    }

    /// Get a parallel iterator of mutable references to Atoms making up this Conformer.
    #[doc_cfg(feature = "rayon")]
    pub fn par_atoms_mut(&mut self) -> impl ParallelIterator<Item = &mut Atom> + '_ {
        self.atoms.par_iter_mut()
    }

    /// Add a new atom to the list of atoms making up this Conformer.
    /// ## Arguments
    /// * `new_atom` - the new Atom to add
    pub fn add_atom(&mut self, new_atom: Atom) {
        self.atoms.push(new_atom);
    }

    /// Returns whether this Conformer is an amino acid.
    pub fn is_amino_acid(&self) -> bool {
        reference_tables::is_amino_acid(self.name())
    }

    /// Remove all Atoms matching the given predicate. As this is done in place this is the fastest way to remove Atoms from this Conformer.
    pub fn remove_atoms_by<F>(&mut self, predicate: F)
    where
        F: Fn(&Atom) -> bool,
    {
        self.atoms.retain(|atom| !predicate(atom));
    }

    /// Remove the Atom specified.
    ///
    /// ## Arguments
    /// * `index` - the index of the atom to remove
    ///
    /// ## Panics
    /// Panics if the index is out of bounds.
    pub fn remove_atom(&mut self, index: usize) {
        self.atoms.remove(index);
    }

    /// Remove the specified Atom. Returns `true` if a matching Atom was found and removed.
    /// Removes the first matching Atom from the list.
    ///
    /// ## Arguments
    /// * `serial_number` - the serial number of the Atom to remove
    ///
    /// ## Panics
    /// Panics if the index is out of bounds.
    pub fn remove_atom_by_serial_number(&mut self, serial_number: usize) -> bool {
        let index = self
            .atoms()
            .position(|a| a.serial_number() == serial_number);

        if let Some(i) = index {
            self.remove_atom(i);
            true
        } else {
            false
        }
    }

    /// Remove the specified Atom. Returns `true` if a matching Atom was found and removed.
    /// Removes the first matching Atom from the list. Matching is done in parallel.
    ///
    /// ## Arguments
    /// * `serial_number` - the serial number of the Atom to remove
    ///
    /// ## Panics
    /// Panics if the index is out of bounds.
    #[doc_cfg(feature = "rayon")]
    pub fn par_remove_atom_by_serial_number(&mut self, serial_number: usize) -> bool {
        let index = self
            .atoms
            .par_iter()
            .position_first(|a| a.serial_number() == serial_number);

        if let Some(i) = index {
            self.remove_atom(i);
            true
        } else {
            false
        }
    }

    /// Remove the specified Atom. Returns `true` if a matching Atom was found and removed.
    /// Removes the first matching Atom from the list.
    ///
    /// ## Arguments
    /// * `name` - the name of the Atom to remove
    ///
    /// ## Panics
    /// Panics if the index is out of bounds.
    pub fn remove_atom_by_name(&mut self, name: impl AsRef<str>) -> bool {
        let name = name.as_ref();
        let index = self.atoms().position(|a| a.name() == name);

        if let Some(i) = index {
            self.remove_atom(i);
            true
        } else {
            false
        }
    }

    /// Remove the specified Atom. Returns `true` if a matching Atom was found and removed.
    /// Removes the first matching Atom from the list. Matching is done in parallel.
    ///
    /// ## Arguments
    /// * `name` - the name of the Atom to remove
    ///
    /// ## Panics
    /// Panics if the index is out of bounds.
    #[doc_cfg(feature = "rayon")]
    pub fn par_remove_atom_by_name(&mut self, name: impl AsRef<str>) -> bool {
        let name = name.as_ref();
        let index = self.atoms.par_iter().position_first(|a| a.name() == name);

        if let Some(i) = index {
            self.remove_atom(i);
            true
        } else {
            false
        }
    }

    /// Apply a transformation to the position of all atoms making up this Conformer, the new position is immediately set.
    pub fn apply_transformation(&mut self, transformation: &TransformationMatrix) {
        for atom in self.atoms_mut() {
            atom.apply_transformation(transformation);
        }
    }

    /// Apply a transformation to the position of all atoms making up this Conformer, the new position is immediately set.
    /// This is done in parallel.
    #[doc_cfg(feature = "rayon")]
    pub fn par_apply_transformation(&mut self, transformation: &TransformationMatrix) {
        self.par_atoms_mut()
            .for_each(|a| a.apply_transformation(transformation));
    }

    /// Join this Conformer with another Conformer, this moves all atoms from the other Conformer
    /// to this Conformer. All other (meta) data of this Conformer will stay the same.
    pub fn join(&mut self, other: Conformer) {
        self.atoms.extend(other.atoms);
    }

    /// Sort the Atoms of this Conformer.
    pub fn sort(&mut self) {
        self.atoms.sort();
    }

    /// Sort the Atoms of this Conformer in parallel.
    #[doc_cfg(feature = "rayon")]
    pub fn par_sort(&mut self) {
        self.atoms.par_sort();
    }
}

#[allow(clippy::use_debug)]
impl fmt::Display for Conformer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "CONFORMER ID:{:?}, Atoms:{}",
            self.id(),
            self.atoms.len(),
        )
    }
}

impl PartialOrd for Conformer {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.id().cmp(&other.id()))
    }
}

impl Ord for Conformer {
    fn cmp(&self, other: &Self) -> Ordering {
        self.id().cmp(&other.id())
    }
}

impl Extend<Atom> for Conformer {
    /// Extend the Atoms on this Conformer by the given iterator over Atoms.
    fn extend<T: IntoIterator<Item = Atom>>(&mut self, iter: T) {
        self.atoms.extend(iter);
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn test_text_validation() {
        let mut a = Conformer::new("A", None, None).unwrap();
        assert_eq!(Conformer::new("R̊", None, None), None);
        assert!(!a.set_name("Oͦ"));
        assert_eq!(a.name(), "A");
        a.set_name("atom");
        assert_eq!(a.name(), "ATOM");

        assert!(a.set_alternative_location("A"));
        assert!(!a.set_alternative_location("Aͦ"));
        assert_eq!(a.alternative_location(), Some("A"));

        assert!(a
            .set_modification(("ALA".to_string(), "Alanine".to_string()))
            .is_ok());
        assert!(a
            .set_modification(("ALAͦ".to_string(), "Alanine".to_string()))
            .is_err());
        assert!(a
            .set_modification(("ALA".to_string(), "Aͦlanine".to_string()))
            .is_err());
    }

    #[test]
    fn ordering_and_equality() {
        let a = Conformer::new("A", None, None).unwrap();
        let b = Conformer::new("A", None, None).unwrap();
        let c = Conformer::new("B", None, None).unwrap();
        assert_eq!(a, b);
        assert_ne!(a, c);
        assert!(a < c);
        assert!(b < c);
    }

    #[test]
    fn test_empty() {
        let a = Conformer::new("A", None, None).unwrap();
        assert_eq!(a.modification(), None);
        assert_eq!(a.atom_count(), 0);
    }

    #[test]
    fn test_atom() {
        let mut a = Conformer::new("A", None, None).unwrap();
        let mut atom1 = Atom::new(false, 12, "CB", 1.0, 1.0, 1.0, 1.0, 1.0, "C", 0).unwrap();
        let atom2 = Atom::new(false, 13, "CB", 1.0, 1.0, 1.0, 1.0, 1.0, "C", 0).unwrap();
        a.add_atom(atom1.clone());
        a.add_atom(atom2.clone());
        a.add_atom(atom2);
        assert_eq!(a.atom(0), Some(&atom1));
        assert_eq!(a.atom_mut(0), Some(&mut atom1));
        a.remove_atom(0);
        assert!(a.remove_atom_by_name("CB"));
        assert!(a.remove_atom_by_serial_number(13));
        assert_eq!(a.atom_count(), 0);
    }

    #[test]
    fn check_display() {
        let a = Conformer::new("A", None, None).unwrap();
        format!("{a:?}");
        format!("{a}");
    }
}