rust-sasa 0.9.2

RustSASA is a Rust library for computing the absolute solvent accessible surface area (ASA/SASA) of each atom in a given protein structure using the Shrake-Rupley algorithm.
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
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// Copyright (c) 2024 Maxwell Campbell. Licensed under the MIT License.
use crate::structures::atomic::{ChainResult, ProteinResult, ResidueResult};
use crate::utils::consts::{POLAR_AMINO_ACIDS, load_radii_from_file};
use crate::utils::{combine_hash, get_radius, serialize_chain_id, simd_sum};
use crate::{Atom, calculate_sasa_internal};
use fnv::FnvHashMap;
use pdbtbx::PDB;
use snafu::OptionExt;
use snafu::prelude::*;
use std::marker::PhantomData;

/// Options for configuring SASA (Solvent Accessible Surface Area) calculations.
///
/// This struct provides configuration options for SASA calculations at different levels
/// of granularity (atom, residue, chain, or protein level). The type parameter `T`
/// determines the output type and processing behavior.
///
/// # Type Parameters
///
/// * `T` - The processing level, which must implement [`SASAProcessor`]. Available levels:
///   - [`AtomLevel`] - Returns SASA values for individual atoms
///   - [`ResidueLevel`] - Returns SASA values aggregated by residue
///   - [`ChainLevel`] - Returns SASA values aggregated by chain
///   - [`ProteinLevel`] - Returns SASA values aggregated for the entire protein
///
/// # Fields
///
/// * `probe_radius` - Radius of the solvent probe sphere in Angstroms (default: 1.4)
/// * `n_points` - Number of points on the sphere surface for sampling (default: 100)
/// * `threads` - Number of threads to use for parallel processing (default: -1 for all cores)
/// * `include_hydrogens` - Whether to include hydrogen atoms in calculations (default: false)
/// * `radii_config` - Optional custom radii configuration (default: uses embedded protor.config)
/// * `allow_vdw_fallback` - Allow fallback to PDBTBX van der Waals radii when radius is not found in radii file (default: false)
/// * `include_hetatms` - Whether to include HETATM records (e.g. non-standard amino acids) in calculations (default: false)
///
/// # Examples
///
/// ```rust
/// use rust_sasa::options::{SASAOptions, ResidueLevel};
/// use pdbtbx::PDB;
///
/// // Create options with default settings
/// let options = SASAOptions::<ResidueLevel>::new();
///
/// // Customize the configuration
/// let custom_options = SASAOptions::<ResidueLevel>::new()
///     .with_probe_radius(1.2)
///     .with_n_points(200)
///     .with_threads(-1)
///     .with_include_hydrogens(false)
///     .with_allow_vdw_fallback(true)
///     .with_include_hetatms(false);
///
/// // Process a PDB structure
/// # let pdb = PDB::new();
/// let result = custom_options.process(&pdb)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
pub struct SASAOptions<T> {
    probe_radius: f32,
    n_points: usize,
    threads: isize,
    include_hydrogens: bool,
    radii_config: Option<FnvHashMap<String, FnvHashMap<String, f32>>>,
    allow_vdw_fallback: bool,
    include_hetatms: bool,
    read_radii_from_occupancy: bool,
    _marker: PhantomData<T>,
}

// Zero-sized marker types for each level
pub struct AtomLevel;
pub struct ResidueLevel;
pub struct ChainLevel;
pub struct ProteinLevel;

pub type AtomsMappingResult = Result<(Vec<Atom>, FnvHashMap<isize, Vec<usize>>), SASACalcError>;

/// Macro to reduce duplication in atom building logic
macro_rules! build_atom {
    ($atoms:expr, $atom:expr, $element:expr, $residue_name:expr, $atom_name:expr, $parent_id:expr, $radii_config:expr, $allow_vdw_fallback:expr, $read_radii_from_occupancy:expr, $id:expr) => {{
        let radius = if $read_radii_from_occupancy {
            $atom.occupancy() as f32
        } else {
            match get_radius($residue_name, $atom_name, $radii_config) {
                Some(r) => r,
                None => {
                    if $allow_vdw_fallback {
                        $element
                            .atomic_radius()
                            .van_der_waals
                            .context(VanDerWaalsMissingSnafu)? as f32
                    } else {
                        return Err(SASACalcError::RadiusMissing {
                            residue_name: $residue_name.to_string(),
                            atom_name: $atom_name.to_string(),
                            element: $element.to_string(),
                        });
                    }
                }
            }
        };

        $atoms.push(Atom {
            position: [
                $atom.pos().0 as f32,
                $atom.pos().1 as f32,
                $atom.pos().2 as f32,
            ],
            radius,
            id: $id as usize,
            parent_id: $parent_id,
        });
    }};
}

// Trait that defines the processing behavior for each level
pub trait SASAProcessor {
    type Output;

    fn process_atoms(
        atoms: &[Atom],
        atom_sasa: &[f32],
        pdb: &PDB,
        parent_to_atoms: &FnvHashMap<isize, Vec<usize>>,
    ) -> Result<Self::Output, SASACalcError>;

    fn build_atoms_and_mapping(
        pdb: &PDB,
        radii_config: Option<&FnvHashMap<String, FnvHashMap<String, f32>>>,
        allow_vdw_fallback: bool,
        include_hydrogens: bool,
        include_hetatms: bool,
        read_radii_from_occupancy: bool,
    ) -> AtomsMappingResult;
}

impl SASAProcessor for AtomLevel {
    type Output = Vec<f32>;

    fn process_atoms(
        _atoms: &[Atom],
        atom_sasa: &[f32],
        _pdb: &PDB,
        _parent_to_atoms: &FnvHashMap<isize, Vec<usize>>,
    ) -> Result<Self::Output, SASACalcError> {
        Ok(atom_sasa.to_vec())
    }

    fn build_atoms_and_mapping(
        pdb: &PDB,
        radii_config: Option<&FnvHashMap<String, FnvHashMap<String, f32>>>,
        allow_vdw_fallback: bool,
        include_hydrogens: bool,
        include_hetatms: bool,
        read_radii_from_occupancy: bool,
    ) -> Result<(Vec<Atom>, FnvHashMap<isize, Vec<usize>>), SASACalcError> {
        let mut atoms = vec![];
        for residue in pdb.residues() {
            let residue_name = residue.name().context(FailedToGetResidueNameSnafu)?;
            if let Some(conformer) = residue.conformers().next() {
                for atom in conformer.atoms() {
                    let element = atom.element().context(ElementMissingSnafu)?;
                    let atom_name = atom.name();
                    if element == &pdbtbx::Element::H && !include_hydrogens {
                        continue;
                    };
                    if atom.hetero() && !include_hetatms {
                        continue;
                    }
                    let conformer_alt = conformer.alternative_location().unwrap_or("");
                    build_atom!(
                        atoms,
                        atom,
                        element,
                        residue_name,
                        atom_name,
                        None,
                        radii_config,
                        allow_vdw_fallback,
                        read_radii_from_occupancy,
                        combine_hash(&(conformer_alt, atom.serial_number()))
                    );
                }
            }
        }
        Ok((atoms, FnvHashMap::default()))
    }
}

impl SASAProcessor for ResidueLevel {
    type Output = Vec<ResidueResult>;

    fn process_atoms(
        _atoms: &[Atom],
        atom_sasa: &[f32],
        pdb: &PDB,
        parent_to_atoms: &FnvHashMap<isize, Vec<usize>>,
    ) -> Result<Self::Output, SASACalcError> {
        let mut residue_sasa = vec![];
        for chain in pdb.chains() {
            for residue in chain.residues() {
                let residue_key = combine_hash(&(
                    chain.id(),
                    residue.serial_number(),
                    residue.insertion_code().unwrap_or_default(),
                ));
                let residue_atom_index = parent_to_atoms
                    .get(&residue_key)
                    .context(AtomMapToLevelElementFailedSnafu)?;
                let residue_atoms: Vec<_> = residue_atom_index
                    .iter()
                    .map(|&index| atom_sasa[index])
                    .collect();
                let sum = simd_sum(residue_atoms.as_slice());
                let name = residue
                    .name()
                    .context(FailedToGetResidueNameSnafu)?
                    .to_string();
                residue_sasa.push(ResidueResult {
                    serial_number: residue.serial_number(),
                    insertion_code: residue.insertion_code().unwrap_or_default().to_string(),
                    value: sum,
                    is_polar: POLAR_AMINO_ACIDS.contains(&name),
                    chain_id: chain.id().to_string(),
                    name,
                })
            }
        }
        Ok(residue_sasa)
    }

    fn build_atoms_and_mapping(
        pdb: &PDB,
        radii_config: Option<&FnvHashMap<String, FnvHashMap<String, f32>>>,
        allow_vdw_fallback: bool,
        include_hydrogens: bool,
        include_hetatms: bool,
        read_radii_from_occupancy: bool,
    ) -> Result<(Vec<Atom>, FnvHashMap<isize, Vec<usize>>), SASACalcError> {
        let mut atoms = vec![];
        let mut parent_to_atoms = FnvHashMap::default();
        let mut i = 0;
        for chain in pdb.chains() {
            let chain_id = chain.id();
            for residue in chain.residues() {
                let residue_name = residue.name().context(FailedToGetResidueNameSnafu)?;
                let residue_key = combine_hash(&(
                    chain_id,
                    residue.serial_number(),
                    residue.insertion_code().unwrap_or_default(),
                ));
                let mut temp = vec![];
                if let Some(conformer) = residue.conformers().next() {
                    for atom in conformer.atoms() {
                        let element = atom.element().context(ElementMissingSnafu)?;
                        let atom_name = atom.name();
                        if element == &pdbtbx::Element::H && !include_hydrogens {
                            continue;
                        };
                        if atom.hetero() && !include_hetatms {
                            continue;
                        }
                        let conformer_alt = conformer.alternative_location().unwrap_or("");
                        build_atom!(
                            atoms,
                            atom,
                            element,
                            residue_name,
                            atom_name,
                            Some(residue.serial_number()),
                            radii_config,
                            allow_vdw_fallback,
                            read_radii_from_occupancy,
                            combine_hash(&(conformer_alt, atom.serial_number()))
                        );
                        temp.push(i);
                        i += 1;
                    }
                    parent_to_atoms.insert(residue_key, temp);
                }
            }
        }
        Ok((atoms, parent_to_atoms))
    }
}

impl SASAProcessor for ChainLevel {
    type Output = Vec<ChainResult>;

    fn process_atoms(
        _atoms: &[Atom],
        atom_sasa: &[f32],
        pdb: &PDB,
        parent_to_atoms: &FnvHashMap<isize, Vec<usize>>,
    ) -> Result<Self::Output, SASACalcError> {
        let mut chain_sasa = vec![];
        for chain in pdb.chains() {
            let chain_id = serialize_chain_id(chain.id());
            let chain_atom_index = parent_to_atoms
                .get(&chain_id)
                .context(AtomMapToLevelElementFailedSnafu)?;
            let chain_atoms: Vec<_> = chain_atom_index
                .iter()
                .map(|&index| atom_sasa[index])
                .collect();
            let sum = simd_sum(chain_atoms.as_slice());
            chain_sasa.push(ChainResult {
                name: chain.id().to_string(),
                value: sum,
            })
        }
        Ok(chain_sasa)
    }

    fn build_atoms_and_mapping(
        pdb: &PDB,
        radii_config: Option<&FnvHashMap<String, FnvHashMap<String, f32>>>,
        allow_vdw_fallback: bool,
        include_hydrogens: bool,
        include_hetatms: bool,
        read_radii_from_occupancy: bool,
    ) -> Result<(Vec<Atom>, FnvHashMap<isize, Vec<usize>>), SASACalcError> {
        let mut atoms = vec![];
        let mut parent_to_atoms = FnvHashMap::default();
        let mut i = 0;
        for chain in pdb.chains() {
            let chain_id = serialize_chain_id(chain.id());
            let mut temp = vec![];
            for residue in chain.residues() {
                let residue_name = residue.name().context(FailedToGetResidueNameSnafu)?;
                if let Some(conformer) = residue.conformers().next() {
                    for atom in conformer.atoms() {
                        let element = atom.element().context(ElementMissingSnafu)?;
                        let atom_name = atom.name();
                        let conformer_alt = conformer.alternative_location().unwrap_or("");
                        if element == &pdbtbx::Element::H && !include_hydrogens {
                            continue;
                        };
                        if atom.hetero() && !include_hetatms {
                            continue;
                        }
                        build_atom!(
                            atoms,
                            atom,
                            element,
                            residue_name,
                            atom_name,
                            Some(chain_id),
                            radii_config,
                            allow_vdw_fallback,
                            read_radii_from_occupancy,
                            combine_hash(&(conformer_alt, atom.serial_number()))
                        );
                        temp.push(i);
                        i += 1
                    }
                }
            }
            parent_to_atoms.insert(chain_id, temp);
        }
        Ok((atoms, parent_to_atoms))
    }
}

impl SASAProcessor for ProteinLevel {
    type Output = ProteinResult;

    fn process_atoms(
        _atoms: &[Atom],
        atom_sasa: &[f32],
        pdb: &PDB,
        parent_to_atoms: &FnvHashMap<isize, Vec<usize>>,
    ) -> Result<Self::Output, SASACalcError> {
        let mut polar_total: f32 = 0.0;
        let mut non_polar_total: f32 = 0.0;
        for chain in pdb.chains() {
            for residue in chain.residues() {
                let residue_key = combine_hash(&(
                    chain.id(),
                    residue.serial_number(),
                    residue.insertion_code().unwrap_or_default(),
                ));
                let residue_atom_index = parent_to_atoms
                    .get(&residue_key)
                    .context(AtomMapToLevelElementFailedSnafu)?;
                let residue_atoms: Vec<_> = residue_atom_index
                    .iter()
                    .map(|&index| atom_sasa[index])
                    .collect();
                let sum = simd_sum(residue_atoms.as_slice());
                let name = residue
                    .name()
                    .context(FailedToGetResidueNameSnafu)?
                    .to_string();
                if POLAR_AMINO_ACIDS.contains(&name) {
                    polar_total += sum
                } else {
                    non_polar_total += sum
                }
            }
        }
        let global_sum = simd_sum(atom_sasa);
        Ok(ProteinResult {
            global_total: global_sum,
            polar_total,
            non_polar_total,
        })
    }

    fn build_atoms_and_mapping(
        pdb: &PDB,
        radii_config: Option<&FnvHashMap<String, FnvHashMap<String, f32>>>,
        allow_vdw_fallback: bool,
        include_hydrogens: bool,
        include_hetatms: bool,
        read_radii_from_occupancy: bool,
    ) -> Result<(Vec<Atom>, FnvHashMap<isize, Vec<usize>>), SASACalcError> {
        let mut atoms = vec![];
        let mut parent_to_atoms = FnvHashMap::default();
        let mut i = 0;
        for chain in pdb.chains() {
            let chain_id = chain.id();
            for residue in chain.residues() {
                let residue_name = residue.name().context(FailedToGetResidueNameSnafu)?;
                let residue_key = combine_hash(&(
                    chain_id,
                    residue.serial_number(),
                    residue.insertion_code().unwrap_or_default(),
                ));
                let mut temp = vec![];
                if let Some(conformer) = residue.conformers().next() {
                    for atom in conformer.atoms() {
                        let element = atom.element().context(ElementMissingSnafu)?;
                        let atom_name = atom.name();
                        if element == &pdbtbx::Element::H && !include_hydrogens {
                            continue;
                        };
                        if atom.hetero() && !include_hetatms {
                            continue;
                        }
                        build_atom!(
                            atoms,
                            atom,
                            element,
                            residue_name,
                            atom_name,
                            Some(residue.serial_number()),
                            radii_config,
                            allow_vdw_fallback,
                            read_radii_from_occupancy,
                            combine_hash(&("", atom.serial_number()))
                        );
                        temp.push(i);
                        i += 1;
                    }
                    parent_to_atoms.insert(residue_key, temp);
                }
            }
        }
        Ok((atoms, parent_to_atoms))
    }
}

#[derive(Debug, Snafu)]
pub enum SASACalcError {
    #[snafu(display("Element missing for atom"))]
    ElementMissing,

    #[snafu(display("Van der Waals radius missing for element"))]
    VanDerWaalsMissing,

    #[snafu(display(
        "Radius not found for residue '{}' atom '{}' of type '{}'. This error can can be ignored, if you are using the CLI pass --allow-vdw-fallback or use with_allow_vdw_fallback if you are using the API.",
        residue_name,
        atom_name,
        element
    ))]
    RadiusMissing {
        residue_name: String,
        atom_name: String,
        element: String,
    },

    #[snafu(display("Failed to map atoms back to level element"))]
    AtomMapToLevelElementFailed,

    #[snafu(display("Failed to get residue name"))]
    FailedToGetResidueName,

    #[snafu(display("Failed to load radii file: {source}"))]
    RadiiFileLoad { source: std::io::Error },
}

impl<T> SASAOptions<T> {
    /// Create a new SASAOptions with the specified level type
    pub fn new() -> SASAOptions<T> {
        SASAOptions {
            probe_radius: 1.4,
            n_points: 100,
            threads: -1,
            include_hydrogens: false,
            radii_config: None,
            allow_vdw_fallback: false,
            include_hetatms: false,
            read_radii_from_occupancy: false,
            _marker: PhantomData,
        }
    }

    /// Set the probe radius (default: 1.4 Angstroms)
    pub fn with_probe_radius(mut self, radius: f32) -> Self {
        self.probe_radius = radius;
        self
    }

    /// Include or exclude HETATM records in protein.
    pub fn with_include_hetatms(mut self, include_hetatms: bool) -> Self {
        self.include_hetatms = include_hetatms;
        self
    }

    /// Set the number of points on the sphere for sampling (default: 100)
    pub fn with_n_points(mut self, points: usize) -> Self {
        self.n_points = points;
        self
    }

    /// Set whether radii should be read from input protein occupancy values. (default: false)
    pub fn with_read_radii_from_occupancy(mut self, read_radii_from_occupancy: bool) -> Self {
        self.read_radii_from_occupancy = read_radii_from_occupancy;
        self
    }

    /// Configure the number of threads to use for parallel processing
    ///   - `-1`: Use all available CPU cores (default)
    ///   - `1`: Single-threaded execution (disables parallelism)
    ///   - `> 1`: Use specified number of threads
    pub fn with_threads(mut self, threads: isize) -> Self {
        self.threads = threads;
        self
    }

    /// Include or exclude hydrogen atoms in calculations (default: false)
    pub fn with_include_hydrogens(mut self, include_hydrogens: bool) -> Self {
        self.include_hydrogens = include_hydrogens;
        self
    }

    /// Load custom radii configuration from a file (default: uses embedded protor.config)
    pub fn with_radii_file(mut self, path: &str) -> Result<Self, std::io::Error> {
        self.radii_config = Some(load_radii_from_file(path)?);
        Ok(self)
    }

    /// Allow fallback to PDBTBX van der Waals radii when radius is not found in radii config file (default: false)
    pub fn with_allow_vdw_fallback(mut self, allow: bool) -> Self {
        self.allow_vdw_fallback = allow;
        self
    }
}

// Convenience constructors for each level
impl SASAOptions<AtomLevel> {
    pub fn atom_level() -> Self {
        Self::new()
    }
}

impl SASAOptions<ResidueLevel> {
    pub fn residue_level() -> Self {
        Self::new()
    }
}

impl SASAOptions<ChainLevel> {
    pub fn chain_level() -> Self {
        Self::new()
    }
}

impl SASAOptions<ProteinLevel> {
    pub fn protein_level() -> Self {
        Self::new()
    }
}

impl<T> Default for SASAOptions<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: SASAProcessor> SASAOptions<T> {
    /// This function calculates the SASA for a given protein. The output type is determined by the level type parameter.
    /// Probe radius and n_points can be customized, defaulting to 1.4 and 100 respectively.
    /// If you want more fine-grained control you may want to use [calculate_sasa_internal] instead.
    /// ## Example
    /// ```
    /// use pdbtbx::StrictnessLevel;
    /// use rust_sasa::options::{SASAOptions, ResidueLevel};
    /// let (mut pdb, _errors) = pdbtbx::open("./tests/data/pdbs/example.cif").unwrap();
    /// let result = SASAOptions::<ResidueLevel>::new().process(&pdb);
    /// ```
    pub fn process(&self, pdb: &PDB) -> Result<T::Output, SASACalcError> {
        let (atoms, parent_to_atoms) = T::build_atoms_and_mapping(
            pdb,
            self.radii_config.as_ref(),
            self.allow_vdw_fallback,
            self.include_hydrogens,
            self.include_hetatms,
            self.read_radii_from_occupancy,
        )?;
        let atom_sasa =
            calculate_sasa_internal(&atoms, self.probe_radius, self.n_points, self.threads);
        T::process_atoms(&atoms, &atom_sasa, pdb, &parent_to_atoms)
    }
}