molframe-cif 0.6.1

PDBx/mmCIF reading and writing 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
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
//! Fallible canonical projection from semantic structure data to mmCIF.
//!
//! Validation completes before output allocation, so failure never returns a
//! partial file. Values that CIF explicitly permits to be unknown remain
//! sentinels; identifiers required to address atoms, models, and bond endpoints
//! are never invented implicitly.

use super::options::{CifWriteError, CifWriteOptions, CifWriteToError};
use super::projection::{
    CanonicalAtomRow, CanonicalProjection, CanonicalValue, canonical_projection,
};
use super::value::quoted;
use molframe_core::io::TextOutput;
use molframe_core::structure::Structure;
use molframe_core::topology::EntityKind;
use std::fmt::{self, Display, Formatter, Write as _};
use std::io::Write as IoWrite;

/// Writes a structure using only identifiers retained in the structure.
///
/// # Errors
///
/// Returns [`CifWriteError`] before allocating output when a required identity
/// is absent or connectivity would require generated connection identifiers.
pub fn write_canonical(structure: &Structure) -> Result<String, CifWriteError> {
    write_canonical_with_options(structure, &CifWriteOptions::new())
}

/// Writes a structure with explicit choices for identities not retained by the graph.
///
/// # Errors
///
/// Returns [`CifWriteError`] before allocating output when preflight finds an
/// unrepresentable atom, model, bond endpoint, or block identifier.
pub fn write_canonical_with_options(
    structure: &Structure,
    options: &CifWriteOptions,
) -> Result<String, CifWriteError> {
    let mut out = String::with_capacity(structure.atom_count() as usize * 100);
    render_canonical(&mut out, structure, options)?;
    Ok(out)
}

/// Streams canonical mmCIF directly to a byte destination.
///
/// Projection validation completes before the first write. The writer retains
/// no atom rows and uses only formatting-sized temporary storage.
///
/// # Errors
///
/// Returns a canonical projection refusal or the destination I/O error.
pub fn write_canonical_to<W: IoWrite>(
    structure: &Structure,
    options: &CifWriteOptions,
    output: &mut W,
) -> Result<(), CifWriteToError> {
    let mut output = TextOutput::new(output);
    render_canonical(&mut output, structure, options)?;
    output.finish().map_err(CifWriteToError::Output)
}

fn render_canonical(
    out: &mut impl fmt::Write,
    structure: &Structure,
    options: &CifWriteOptions,
) -> Result<(), CifWriteError> {
    // mmCIF keys a chain by its normalised label, so chains that repeat one
    // must be told apart or they merge when the file is read back.
    let distinct = structure.with_distinct_labels();
    let structure = match distinct.as_ref() {
        Some(distinct) => distinct,
        None => structure,
    };
    let projection = canonical_projection(structure, options)?;
    let _ = writeln!(out, "data_{}", projection.block_id());
    let _ = out.write_str("#\n");
    write_entry_metadata(out, structure);
    write_cell(out, structure);
    write_entities(out, structure);
    super::references::write(out, structure);
    super::supplement::write(out, structure, options);
    write_atoms(out, projection)?;
    super::bonds::write(out, structure)?;
    write_anisotropy(out, structure);
    Ok(())
}

fn write_entry_metadata(out: &mut impl fmt::Write, structure: &Structure) {
    let entry = &structure.data().entry;
    if let Some(id) = &entry.id {
        let _ = writeln!(out, "_entry.id   {}\n#", quoted(id));
    }
    if let Some(title) = &entry.title {
        let _ = writeln!(out, "_struct.title   {}\n#", quoted(title));
    }
    if let Some(method) = &entry.method {
        let _ = writeln!(out, "_exptl.method   {}\n#", quoted(method));
    }
}

fn write_cell(out: &mut impl fmt::Write, structure: &Structure) {
    let Some(cell) = structure.data().cell else {
        return;
    };
    let _ = writeln!(
        out,
        "_cell.length_a      {:.4}\n_cell.length_b      {:.4}\n_cell.length_c      {:.4}\n\
         _cell.angle_alpha   {:.4}\n_cell.angle_beta    {:.4}\n_cell.angle_gamma   {:.4}\n#",
        cell.lengths[0],
        cell.lengths[1],
        cell.lengths[2],
        cell.angles[0],
        cell.angles[1],
        cell.angles[2],
    );
}

fn write_entities(out: &mut impl fmt::Write, structure: &Structure) {
    let entities = &structure.data().topology.entities;
    if entities.is_empty() {
        return;
    }
    let _ = out.write_str("loop_\n_entity.id\n_entity.type\n_entity.pdbx_description\n");
    for entity in entities.iter() {
        let id = symbol_or_dot(structure, entities.id(entity));
        let kind = match entities.kind(entity) {
            Some(EntityKind::Polymer) => "polymer",
            Some(EntityKind::NonPolymer) => "non-polymer",
            Some(EntityKind::Water) => "water",
            Some(EntityKind::Branched) => "branched",
            _ => "?",
        };
        let description = symbol_or_dot(structure, entities.description(entity));
        let _ = writeln!(out, "{id} {kind} {description}");
    }
    let _ = out.write_str("#\n");
    write_entity_polymers(out, structure);
    write_entity_sequences(out, structure);
}

fn write_entity_polymers(out: &mut impl fmt::Write, structure: &Structure) {
    let declared = super::declared_polymer_types(structure);
    if declared.is_empty() {
        return;
    }
    let entities = &structure.data().topology.entities;
    let _ = out.write_str("loop_\n_entity_poly.entity_id\n_entity_poly.type\n");
    for (entity, kind) in declared {
        let id = symbol_or_dot(structure, entities.id(entity));
        let _ = writeln!(out, "{id} {}", quoted(kind));
    }
    let _ = out.write_str("#\n");
}

fn write_entity_sequences(out: &mut impl fmt::Write, structure: &Structure) {
    let entities = &structure.data().topology.entities;
    if !entities
        .iter()
        .any(|entity| !entities.canonical_sequence(entity).is_empty())
    {
        return;
    }
    let _ = out.write_str(
        "loop_\n_entity_poly_seq.entity_id\n_entity_poly_seq.num\n_entity_poly_seq.mon_id\n",
    );
    for entity in entities.iter() {
        let id = symbol_or_dot(structure, entities.id(entity));
        for (position, component) in entities.canonical_sequence(entity).iter().enumerate() {
            let component = symbol_or_dot(structure, Some(*component));
            let _ = writeln!(out, "{id} {} {component}", position + 1);
        }
    }
    let _ = out.write_str("#\n");
}

const ATOM_SITE_HEADER: &str = "loop_\n\
_atom_site.group_PDB\n_atom_site.id\n_atom_site.type_symbol\n\
_atom_site.label_atom_id\n_atom_site.label_alt_id\n_atom_site.label_comp_id\n\
_atom_site.label_asym_id\n_atom_site.label_entity_id\n_atom_site.label_seq_id\n\
_atom_site.pdbx_PDB_ins_code\n_atom_site.Cartn_x\n_atom_site.Cartn_y\n\
_atom_site.Cartn_z\n_atom_site.occupancy\n_atom_site.B_iso_or_equiv\n\
_atom_site.auth_seq_id\n_atom_site.auth_comp_id\n_atom_site.auth_asym_id\n\
_atom_site.auth_atom_id\n";

const MODEL_NUMBER_HEADER: &str = "_atom_site.pdbx_PDB_model_num\n";

const FORMAL_CHARGE_HEADER: &str = "_atom_site.pdbx_formal_charge\n";

fn write_atoms(
    out: &mut impl fmt::Write,
    projection: CanonicalProjection<'_>,
) -> Result<(), CifWriteError> {
    let charged = projection.carries_formal_charge();
    let _ = out.write_str(ATOM_SITE_HEADER);
    if charged {
        let _ = out.write_str(FORMAL_CHARGE_HEADER);
    }
    let _ = out.write_str(MODEL_NUMBER_HEADER);
    projection.visit_atom_rows(|row| {
        let _ = write_atom(out, row, charged);
    })?;
    let _ = out.write_str("#\n");
    Ok(())
}

fn write_atom(out: &mut impl fmt::Write, row: CanonicalAtomRow<'_>, charged: bool) -> fmt::Result {
    let element = match row.element() {
        CanonicalValue::Present(item) => ElementValue::Present(item.symbol()),
        CanonicalValue::Inapplicable => ElementValue::Inapplicable,
        CanonicalValue::Unknown => ElementValue::Unknown,
    };
    let charge = ChargeCell { row, charged };
    writeln!(
        out,
        "{} {} {element} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}{charge} {}",
        row.group(),
        row.atom_site_id(),
        quoted(row.label_atom_id()),
        text_value(row.label_alt_id()),
        quoted(row.label_comp_id()),
        quoted(row.label_asym_id()),
        text_value(row.label_entity_id()),
        integer_value(row.label_seq_id()),
        text_value(row.insertion_code()),
        float_value(row.coordinate(0), 3),
        float_value(row.coordinate(1), 3),
        float_value(row.coordinate(2), 3),
        float_value(row.occupancy(), 2),
        float_value(row.b_factor(), 2),
        integer_value(row.auth_seq_id()),
        text_value(row.auth_comp_id()),
        text_value(row.auth_asym_id()),
        text_value(row.auth_atom_id()),
        row.model_number(),
    )
}

/// Writes the `atom_site_anisotrop` category when any atom carries a tensor.
///
/// Rows join back to `atom_site` by the deposited `_atom_site.id` the atom rows
/// themselves carry, so a structure with no deposited identifiers cannot name
/// its rows and the category is left out entirely — the join key would have to
/// be invented.
fn write_anisotropy(out: &mut impl fmt::Write, structure: &Structure) {
    let anisotropy = &structure.data().anisotropy;
    if anisotropy.iter().next().is_none() {
        return;
    }
    let _ = out.write_str(
        "loop_\n\
         _atom_site_anisotrop.id\n\
         _atom_site_anisotrop.type_symbol\n\
         _atom_site_anisotrop.U[1][1]\n\
         _atom_site_anisotrop.U[2][2]\n\
         _atom_site_anisotrop.U[3][3]\n\
         _atom_site_anisotrop.U[1][2]\n\
         _atom_site_anisotrop.U[1][3]\n\
         _atom_site_anisotrop.U[2][3]\n",
    );
    for record in anisotropy.iter() {
        let Some(atom) = structure.atom(record.atom) else {
            continue;
        };
        let Some(id) = atom.atom_site_id().filter(|value| *value != 0) else {
            continue;
        };
        let element = match atom.element() {
            Some(element) => element.symbol(),
            None => "",
        };
        let _ = writeln!(
            out,
            "{} {} {u11} {u22} {u33} {u12} {u13} {u23}",
            id,
            element,
            u11 = u_field(record.u[0]),
            u22 = u_field(record.u[1]),
            u33 = u_field(record.u[2]),
            u12 = u_field(record.u[3]),
            u13 = u_field(record.u[4]),
            u23 = u_field(record.u[5]),
        );
    }
    let _ = out.write_str("#\n");
}

/// One displacement component, written as a decimal ångström-squared value.
fn u_field(value: f32) -> String {
    format!("{value:.5}")
}

fn text_value(value: CanonicalValue<&str>) -> TextValue<'_> {
    TextValue(value)
}

fn integer_value(value: CanonicalValue<i64>) -> IntegerValue {
    IntegerValue(value)
}

fn float_value(value: CanonicalValue<f64>, precision: usize) -> FloatValue {
    FloatValue { value, precision }
}

fn symbol_or_dot(
    structure: &Structure,
    symbol: Option<molframe_core::symbol::SymbolId>,
) -> TextValue<'_> {
    match symbol.and_then(|id| structure.resolve(id)) {
        Some(text) if !text.is_empty() => TextValue(CanonicalValue::Present(text)),
        Some(_) | None => TextValue(CanonicalValue::Inapplicable),
    }
}

struct TextValue<'a>(CanonicalValue<&'a str>);

impl Display for TextValue<'_> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self.0 {
            CanonicalValue::Present(text) => Display::fmt(&quoted(text), formatter),
            CanonicalValue::Inapplicable => formatter.write_str("."),
            CanonicalValue::Unknown => formatter.write_str("?"),
        }
    }
}

struct IntegerValue(CanonicalValue<i64>);

impl Display for IntegerValue {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self.0 {
            CanonicalValue::Present(number) => Display::fmt(&number, formatter),
            CanonicalValue::Inapplicable => formatter.write_str("."),
            CanonicalValue::Unknown => formatter.write_str("?"),
        }
    }
}

struct FloatValue {
    value: CanonicalValue<f64>,
    precision: usize,
}

impl Display for FloatValue {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self.value {
            CanonicalValue::Present(number) => write_shortest(formatter, number, self.precision),
            CanonicalValue::Inapplicable => formatter.write_str("."),
            CanonicalValue::Unknown => formatter.write_str("?"),
        }
    }
}

struct ChargeCell<'a> {
    row: CanonicalAtomRow<'a>,
    charged: bool,
}

impl Display for ChargeCell<'_> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        if !self.charged {
            return Ok(());
        }
        write!(formatter, " {}", integer_value(self.row.formal_charge()))
    }
}

/// Writes the stored single-precision value with the fewest decimals that
/// read back to the same value, never fewer than `minimum`.
fn write_shortest(formatter: &mut Formatter<'_>, number: f64, minimum: usize) -> fmt::Result {
    // The value was widened from single precision, so narrowing is exact.
    let stored = molframe_core::numeric::f64_to_f32(number);
    if !stored.is_finite() {
        return write!(formatter, "{number:.minimum$}");
    }
    let mut decimals = minimum;
    while decimals < 9 {
        let mut probe = Probe {
            bytes: [0; 48],
            length: 0,
        };
        let _ = write!(probe, "{stored:.decimals$}");
        if probe
            .text()
            .parse::<f32>()
            .is_ok_and(|back| back.to_bits() == stored.to_bits())
        {
            break;
        }
        decimals += 1;
    }
    write!(formatter, "{stored:.decimals$}")
}

struct Probe {
    bytes: [u8; 48],
    length: usize,
}

impl Probe {
    fn text(&self) -> &str {
        match std::str::from_utf8(&self.bytes[..self.length]) {
            Ok(text) => text,
            Err(_) => "",
        }
    }
}

impl fmt::Write for Probe {
    fn write_str(&mut self, text: &str) -> fmt::Result {
        let end = self.length + text.len();
        let slot = self.bytes.get_mut(self.length..end).ok_or(fmt::Error)?;
        slot.copy_from_slice(text.as_bytes());
        self.length = end;
        Ok(())
    }
}

enum ElementValue<'a> {
    Present(&'a str),
    Inapplicable,
    Unknown,
}

impl Display for ElementValue<'_> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Present(symbol) => {
                for byte in symbol.bytes() {
                    formatter.write_char(char::from(byte.to_ascii_uppercase()))?;
                }
                Ok(())
            }
            Self::Inapplicable => formatter.write_str("."),
            Self::Unknown => formatter.write_str("?"),
        }
    }
}

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