molframe-core 0.6.3

Core types, storage and analysis contracts for molframe
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
//! Shared parsing options and reader/writer traits.

use super::super::input::{InputBuffer, Limits};
use super::detect::Format;
use crate::diagnostic::Diagnostic;
use crate::diagnostic::{Diagnostics, Strictness};
use crate::structure::Structure;

/// How much irregularity a read tolerates, and what it does about it.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub enum ParseMode {
    /// Anything violating the specification fails the read.
    Strict,
    /// Produce a structure and report what was wrong with it.
    #[default]
    Permissive,
    /// Continue past local errors, marking the regions they affected.
    Recover,
}

impl ParseMode {
    /// The strictness this mode implies.
    #[must_use]
    pub const fn strictness(self) -> Strictness {
        match self {
            Self::Strict => Strictness::Strict,
            Self::Permissive => Strictness::Medium,
            Self::Recover => Strictness::Loose,
        }
    }
}

/// Whether a read infers bonds, components and secondary structure afterwards.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Perception {
    /// Run the perception pass: inferred bonds, standard components, DSSP.
    #[default]
    Infer,
    /// Return the structure as the file states it.
    Skip,
}

/// Whether a read records a digest of the bytes it parsed.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum InputDigest {
    /// Record nothing: hashing is work on every read, and the read path is measured on
    /// throughput.
    #[default]
    Skip,
    /// Record the SHA-256 of the bytes parsed, after decompression.
    Sha256,
}

/// Policy for atom rows whose format-specific element field is absent or invalid.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum MissingElementPolicy {
    /// Preserve the missing value as [`Element::UNKNOWN`](crate::Element::UNKNOWN).
    #[default]
    PreserveUnknown,
    /// Explicitly apply the naming convention of the selected input format.
    InferFromAtomName,
}

/// Policy for atoms whose recorded occupancy lies outside zero to one.
///
/// Every policy reports the condition once per read as `E3009` (or `W3014`
/// when clamped), with the atom count, the first atom and the first value. A
/// `Strict` parse mode rejects the default policy's finding.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum OccupancyPolicy {
    /// Keep the deposited values and report the condition.
    #[default]
    Keep,
    /// Clamp recorded occupancies into zero to one and report the change.
    Clamp,
    /// Fail the read, in any parse mode.
    Reject,
}

/// Policy for adjacent mmCIF atom groups whose residue identifiers are identical.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum AmbiguousResidueBoundaryPolicy {
    /// Refuse to invent a residue boundary that the deposited identifiers do not define.
    #[default]
    Reject,
    /// Explicitly split when an atom name repeats in the same alternate location.
    InferFromFileOrder,
}

/// mmCIF/BinaryCIF categories every structure read needs, whatever the filter.
pub const REQUIRED_CIF_CATEGORIES: [&str; 5] = [
    "atom_site",
    "entity",
    "entity_poly",
    "entity_poly_seq",
    "struct_asym",
];

/// PDB records every structure read needs, whatever the filter.
pub const REQUIRED_PDB_RECORDS: [&str; 6] = ["ATOM", "HETATM", "MODEL", "ENDMDL", "TER", "END"];

/// Categories a retained `struct_conn` needs to be interpreted rather than guessed.
///
/// A connection may name a partner on a neighbouring crystal image. Without the
/// operator table there is nothing to check the named operator against, so the
/// reader would have to assume the local identity — the guess this list exists to
/// make unnecessary.
pub const SYMMETRY_DEPENDENCIES: [&str; 2] = ["space_group_symop", "symmetry_equiv"];

/// Which optional categories (mmCIF/BinaryCIF) or records (PDB) a read keeps.
///
/// Names are compared ASCII case-insensitively. Required names (see
/// [`REQUIRED_CIF_CATEGORIES`], [`REQUIRED_PDB_RECORDS`]) are kept by
/// [`CategoryFilter::keeps_category`] and [`CategoryFilter::keeps_record`]
/// regardless of the filter.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum CategoryFilter {
    /// Keep everything.
    #[default]
    All,
    /// Keep only the named names, plus the required ones.
    Only(Vec<Box<str>>),
    /// Keep everything except the named names, unless required.
    Except(Vec<Box<str>>),
}

impl CategoryFilter {
    /// Keeps only `names` (and the required names).
    #[must_use]
    pub fn only<I, S>(names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<Box<str>>,
    {
        Self::Only(names.into_iter().map(Into::into).collect())
    }

    /// Drops `names`, except those that are required.
    #[must_use]
    pub fn except<I, S>(names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<Box<str>>,
    {
        Self::Except(names.into_iter().map(Into::into).collect())
    }

    /// Whether the filter itself admits `name`, ignoring what is required.
    #[must_use]
    pub fn admits(&self, name: &str) -> bool {
        let listed = |names: &[Box<str>]| names.iter().any(|item| item.eq_ignore_ascii_case(name));
        match self {
            Self::All => true,
            Self::Only(names) => listed(names),
            Self::Except(names) => !listed(names),
        }
    }

    /// Whether a CIF category must be read: required, admitted, or a dependency
    /// of one that is.
    #[must_use]
    pub fn keeps_category(&self, name: &str) -> bool {
        self.admits(name)
            || REQUIRED_CIF_CATEGORIES
                .iter()
                .any(|required| required.eq_ignore_ascii_case(name))
            || self.dependency_admitted(name)
    }

    /// Whether a retained category depends on this one.
    ///
    /// A retained `struct_conn` names its partners through symmetry operators, and
    /// an operator table the filter dropped cannot be shown to be the identity.
    /// Keeping the connections therefore keeps the tables with them: otherwise a
    /// filter would silently turn an explicit nonidentity operator into an implicit
    /// local bond.
    fn dependency_admitted(&self, name: &str) -> bool {
        self.admits("struct_conn")
            && SYMMETRY_DEPENDENCIES
                .iter()
                .any(|dependency| dependency.eq_ignore_ascii_case(name))
    }

    /// Whether a PDB record must be read: required, or admitted.
    #[must_use]
    pub fn keeps_record(&self, name: &str) -> bool {
        self.admits(name)
            || REQUIRED_PDB_RECORDS
                .iter()
                .any(|required| required.eq_ignore_ascii_case(name))
    }
}

/// What a read should and should not bother doing.
#[derive(Clone, Debug, Default)]
pub struct ReadOptions {
    /// Which format, or automatic detection.
    pub format: Format,
    /// How much irregularity to tolerate.
    pub mode: ParseMode,
    /// Read only the first model.
    pub only_first_model: bool,
    /// Read coordinates and skip everything else.
    pub only_atomic_coords: bool,
    /// Skip the perception pass that follows a read: inferred bonds, standard
    /// component annotation and secondary-structure assignment. The parse and
    /// everything the file itself records are unaffected; only what a reader
    /// would otherwise compute from the coordinates is left out.
    pub perception: Perception,
    /// Drop hydrogens while reading.
    pub discard_hydrogens: bool,
    /// What to do when a row does not declare a valid element.
    pub missing_element_policy: MissingElementPolicy,
    /// What to do when a recorded occupancy lies outside zero to one.
    pub occupancy_policy: OccupancyPolicy,
    /// What to do when mmCIF residue identifiers do not define a boundary.
    pub ambiguous_residue_boundary_policy: AmbiguousResidueBoundaryPolicy,
    /// Ceilings that apply while reading.
    pub limits: Limits,
    /// Which optional categories or records to read.
    pub categories: CategoryFilter,
    /// Whether to record the SHA-256 of the bytes parsed in the structure's entry
    /// metadata; only a result certified as computed from exactly these bytes needs it.
    pub input_digest: InputDigest,
}

impl ReadOptions {
    /// Options that read everything, tolerating what the archive contains.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the format.
    #[must_use]
    pub const fn format(mut self, format: Format) -> Self {
        self.format = format;
        self
    }

    /// Sets how much irregularity to tolerate.
    #[must_use]
    pub const fn mode(mut self, mode: ParseMode) -> Self {
        self.mode = mode;
        self
    }

    /// Reads only the first model.
    #[must_use]
    pub const fn only_first_model(mut self, only: bool) -> Self {
        self.only_first_model = only;
        self
    }

    /// Reads coordinates and skips everything else.
    #[must_use]
    pub const fn only_atomic_coords(mut self, only: bool) -> Self {
        self.only_atomic_coords = only;
        self
    }

    /// Chooses whether the perception pass runs after the parse (it does by default).
    ///
    /// Passing `false` returns the structure as the file states it: file bonds and
    /// deposited secondary structure are kept, nothing is inferred from geometry.
    #[must_use]
    pub const fn perceive(mut self, perceive: bool) -> Self {
        self.perception = if perceive {
            Perception::Infer
        } else {
            Perception::Skip
        };
        self
    }

    /// Selects an explicit policy for missing or invalid element fields.
    #[must_use]
    pub const fn missing_element_policy(mut self, policy: MissingElementPolicy) -> Self {
        self.missing_element_policy = policy;
        self
    }

    /// Selects the policy for occupancies outside zero to one.
    #[must_use]
    pub const fn occupancy_policy(mut self, policy: OccupancyPolicy) -> Self {
        self.occupancy_policy = policy;
        self
    }

    /// Selects an explicit policy for ambiguous mmCIF residue boundaries.
    #[must_use]
    pub const fn ambiguous_residue_boundary_policy(
        mut self,
        policy: AmbiguousResidueBoundaryPolicy,
    ) -> Self {
        self.ambiguous_residue_boundary_policy = policy;
        self
    }

    /// Drops hydrogens while reading.
    #[must_use]
    pub const fn discard_hydrogens(mut self, discard: bool) -> Self {
        self.discard_hydrogens = discard;
        self
    }

    /// Restricts which optional categories (mmCIF/BinaryCIF) or records (PDB)
    /// are read. Names the structure cannot be built without are always read.
    #[must_use]
    pub fn categories(mut self, categories: CategoryFilter) -> Self {
        self.categories = categories;
        self
    }

    /// Records the SHA-256 of the bytes parsed, so a result can be tied to them.
    #[must_use]
    pub const fn digest_input(mut self, digest: bool) -> Self {
        self.input_digest = if digest {
            InputDigest::Sha256
        } else {
            InputDigest::Skip
        };
        self
    }

    /// Sets the ceilings that apply while reading.
    #[must_use]
    pub const fn limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Finishes a read under this option set.
    ///
    /// # Errors
    ///
    /// Returns the ordered findings when at least one finding is an error under
    /// the selected parse mode.
    pub fn finish(
        &self,
        structure: Structure,
        findings: impl IntoIterator<Item = Diagnostic>,
    ) -> ReadResult {
        let mut ordered = Diagnostics::new();
        ordered.extend(findings);
        let (structure, reject) =
            super::occupancy::apply(structure, self.occupancy_policy, &mut ordered);
        let is_error = reject || ordered.has_error(self.mode.strictness());
        let findings = ordered.finish();
        if is_error {
            Err(findings)
        } else {
            Ok((structure, findings))
        }
    }
}

/// A structure and everything that was wrong with the file it came from.
pub type ReadResult = Result<(Structure, Vec<Diagnostic>), Vec<Diagnostic>>;

/// A reader for one format.
pub trait Reader {
    /// The format this reads.
    const FORMAT: Format;

    /// Reads a structure.
    ///
    /// # Errors
    ///
    /// Returns the findings that stopped the read.
    fn read(input: &InputBuffer, options: &ReadOptions) -> ReadResult;
}

/// Which parts of a structure a write should include.
pub trait Select {
    /// Whether to write this model.
    fn accept_model(&self, _model: crate::index::ModelIndex) -> bool {
        true
    }

    /// Whether to write this chain.
    fn accept_chain(&self, _chain: crate::index::ChainIndex) -> bool {
        true
    }

    /// Whether to write this residue.
    fn accept_residue(&self, _residue: crate::index::ResidueIndex) -> bool {
        true
    }

    /// Whether to write this atom.
    fn accept_atom(&self, _atom: crate::index::AtomIndex) -> bool {
        true
    }
}

/// A filter that writes everything.
#[derive(Clone, Copy, Debug, Default)]
pub struct SelectAll;

impl Select for SelectAll {}

#[cfg(test)]
#[path = "options_tests.rs"]
mod tests;