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
use crate::error::*;
use crate::structs::*;
use crate::validate;
use crate::StrictnessLevel;

use std::fs::File;
use std::io::prelude::*;
use std::io::BufWriter;

/// Save the given PDB struct to the given file.
/// It validates and renumbers the PDB. It fails if the validation fails with the given `level`.
/// If validation or renumbering gives rise to problems use the `save_raw` function.
pub fn save(mut pdb: PDB, filename: &str, level: StrictnessLevel) -> Result<(), Vec<PDBError>> {
    pdb.renumber();
    let mut errors = validate(&pdb);
    for error in &errors {
        if error.fails(level) {
            return Err(errors);
        }
    }

    let file = match File::create(filename) {
        Ok(f) => f,
        Err(e) => {
            errors.push(PDBError::new(
                ErrorLevel::BreakingError,
                "Could not open file",
                "Could not open the file for writing, make sure you have permission for this file and no other program is currently using it.",
                Context::show(&e.to_string())
            ));
            return Err(errors);
        }
    };

    save_raw(&pdb, BufWriter::new(file));
    Ok(())
}

/// Save the given PDB struct to the given BufWriter.
/// It does not validate or renumber the PDB, so if that is needed that needs to be done in preparation.
pub fn save_raw<T: Write>(pdb: &PDB, mut sink: BufWriter<T>) {
    // Remarks
    for line in pdb.remarks() {
        sink.write_fmt(format_args!("REMARK {:3} {}\n", line.0, line.1))
            .unwrap();
    }

    // Cryst
    if pdb.has_unit_cell() {
        let unit_cell = pdb.unit_cell();
        let sym = if pdb.has_symmetry() {
            format!("{:10}{:3}", pdb.symmetry().symbol(), pdb.symmetry().z(),)
        } else {
            "P 1".to_string()
        };
        sink.write_fmt(format_args!(
            "CRYST1{:9.3}{:9.3}{:9.3}{:7.2}{:7.2}{:7.2} {}\n",
            unit_cell.a(),
            unit_cell.b(),
            unit_cell.c(),
            unit_cell.alpha(),
            unit_cell.beta(),
            unit_cell.gamma(),
            sym
        ))
        .unwrap();
    }

    // Scale
    if pdb.has_scale() {
        let m = pdb.scale().transformation().matrix();
        sink.write_fmt(format_args!(
            "SCALE1    {:10.6}{:10.6}{:10.6}     {:10.5}\nSCALE2    {:10.6}{:10.6}{:10.6}     {:10.5}\nSCALE3    {:10.6}{:10.6}{:10.6}     {:10.5}\n",
            m[0][0],
            m[0][1],
            m[0][2],
            m[0][3],
            m[1][0],
            m[1][1],
            m[1][2],
            m[1][3],
            m[2][0],
            m[2][1],
            m[2][2],
            m[2][3],
        )).unwrap();
    }

    // OrigX
    if pdb.has_origx() {
        let m = pdb.origx().transformation().matrix();
        sink.write_fmt(format_args!(
            "ORIGX1    {:10.6}{:10.6}{:10.6}     {:10.5}\nORIGX2    {:10.6}{:10.6}{:10.6}     {:10.5}\nORIGX3    {:10.6}{:10.6}{:10.6}     {:10.5}\n",
            m[0][0],
            m[0][1],
            m[0][2],
            m[0][3],
            m[1][0],
            m[1][1],
            m[1][2],
            m[1][3],
            m[2][0],
            m[2][1],
            m[2][2],
            m[2][3],
        )).unwrap();
    }

    // MtriX
    for mtrix in pdb.mtrix() {
        let m = mtrix.transformation().matrix();
        sink.write_fmt(format_args!(
            "MTRIX1 {:3}{:10.6}{:10.6}{:10.6}     {:10.5}    {}\nMTRIX2 {:3}{:10.6}{:10.6}{:10.6}     {:10.5}    {}\nMTRIX3 {:3}{:10.6}{:10.6}{:10.6}     {:10.5}    {}\n",
            mtrix.serial_number,
            m[0][0],
            m[0][1],
            m[0][2],
            m[0][3],
            if mtrix.contained {'1'} else {' '},
            mtrix.serial_number,
            m[1][0],
            m[1][1],
            m[1][2],
            m[1][3],
            if mtrix.contained {'1'} else {' '},
            mtrix.serial_number,
            m[2][0],
            m[2][1],
            m[2][2],
            m[2][3],
            if mtrix.contained {'1'} else {' '},
        )).unwrap();
    }

    // Models
    let multiple_models = pdb.models().size_hint().0 > 1;
    for model in pdb.models() {
        if multiple_models {
            sink.write_fmt(format_args!("MODEL        {}\n", model.serial_number()))
                .unwrap();
        }

        for chain in model.chains() {
            for residue in chain.residues() {
                for atom in residue.atoms() {
                    sink
                .write_fmt(format_args!(
                    "ATOM  {:5} {:^4} {:4}{}{:4}    {:8.3}{:8.3}{:8.3}{:6.2}{:6.2}          {:>2}{}\n",
                    atom.serial_number(),
                    atom.name(),
                    residue.id(),
                    chain.id(),
                    residue.serial_number(),
                    atom.pos().0,
                    atom.pos().1,
                    atom.pos().2,
                    atom.occupancy(),
                    atom.b_factor(),
                    atom.element(),
                    atom.pdb_charge(),
                ))
                .unwrap();
                    if atom.anisotropic_temperature_factors().is_some() {
                        sink.write_fmt(format_args!(
                            "ANSIOU{:5} {:^4} {:4}{}{:4}  {:7}{:7}{:7}{:7}{:7}{:7}      {:>2}{}\n",
                            atom.serial_number(),
                            atom.name(),
                            residue.id(),
                            chain.id(),
                            residue.serial_number(),
                            (atom.anisotropic_temperature_factors().unwrap()[0][0] * 10000.0)
                                as isize,
                            (atom.anisotropic_temperature_factors().unwrap()[0][1] * 10000.0)
                                as isize,
                            (atom.anisotropic_temperature_factors().unwrap()[0][2] * 10000.0)
                                as isize,
                            (atom.anisotropic_temperature_factors().unwrap()[1][0] * 10000.0)
                                as isize,
                            (atom.anisotropic_temperature_factors().unwrap()[1][1] * 10000.0)
                                as isize,
                            (atom.anisotropic_temperature_factors().unwrap()[1][2] * 10000.0)
                                as isize,
                            atom.element(),
                            atom.pdb_charge(),
                        ))
                        .unwrap();
                    }
                }
            }
            let last_atom = chain.atoms().nth_back(0).unwrap();
            let last_residue = chain.residues().nth_back(0).unwrap();
            sink.write_fmt(format_args!(
                "TER{:5}      {:3} {}{:4} \n",
                last_atom.serial_number(),
                last_residue.id(),
                chain.id(),
                last_residue.serial_number()
            ))
            .unwrap();
        }
        for chain in model.hetero_chains() {
            for residue in chain.residues() {
                for atom in residue.atoms() {
                    sink
                .write_fmt(format_args!(
                    "HETATM{:5} {:^4} {:4}{}{:4}    {:8.3}{:8.3}{:8.3}{:6.2}{:6.2}          {:>2}{}\n",
                    atom.serial_number(),
                    atom.name(),
                    residue.id(),
                    chain.id(),
                    residue.serial_number(),
                    atom.pos().0,
                    atom.pos().1,
                    atom.pos().2,
                    atom.occupancy(),
                    atom.b_factor(),
                    atom.element(),
                    atom.pdb_charge()
                ))
                .unwrap();
                    if atom.anisotropic_temperature_factors().is_some() {
                        sink.write_fmt(format_args!(
                            "ANSIOU{:5} {:^4} {:4}{}{:4}  {:7}{:7}{:7}{:7}{:7}{:7}      {:>2}{}\n",
                            atom.serial_number(),
                            atom.name(),
                            residue.id(),
                            chain.id(),
                            residue.serial_number(),
                            (atom.anisotropic_temperature_factors().unwrap()[0][0] * 10000.0)
                                as isize,
                            (atom.anisotropic_temperature_factors().unwrap()[0][1] * 10000.0)
                                as isize,
                            (atom.anisotropic_temperature_factors().unwrap()[0][2] * 10000.0)
                                as isize,
                            (atom.anisotropic_temperature_factors().unwrap()[1][0] * 10000.0)
                                as isize,
                            (atom.anisotropic_temperature_factors().unwrap()[1][1] * 10000.0)
                                as isize,
                            (atom.anisotropic_temperature_factors().unwrap()[1][2] * 10000.0)
                                as isize,
                            atom.element(),
                            atom.pdb_charge()
                        ))
                        .unwrap();
                    }
                }
            }
        }

        if multiple_models {
            sink.write_fmt(format_args!("ENDMDL\n")).unwrap();
        }
    }

    let mut xform = 0;
    if pdb.has_origx() && pdb.origx().valid() {
        xform += 3;
    }
    if pdb.has_scale() && pdb.scale().valid() {
        xform += 3;
    }
    for mtrix in pdb.mtrix() {
        if mtrix.valid() {
            xform += 3;
        }
    }
    sink.write_fmt(format_args!(
        "MASTER    {:5}{:5}{:5}{:5}{:5}{:5}{:5}{:5}{:5}{:5}{:5}{:5}\n",
        pdb.remark_count(),
        0, //defined to be empty
        0, //numHet
        0, //numHelix
        0, //numSheet
        0, //numTurn (deprecated)
        0, //numSite
        xform,
        pdb.total_atom_count(),
        pdb.model_count(),
        0, //numConnect
        0, //numSeq
    ))
    .unwrap();
    sink.write_fmt(format_args!("END\n")).unwrap();

    sink.flush().unwrap();
}