use pixelfold_core::interactions::{Interaction, InteractionKind, detect};
use pixelfold_core::sasa::{SurfaceCalculator, relative_sasa};
use pixelfold_core::{Atom, AtomSet, Protein};
use serde::Serialize;
use crate::report::Row;
fn code(insertion: Option<char>) -> String {
insertion.map(String::from).unwrap_or_default()
}
pub(crate) fn rounded(value: f32, places: u32) -> f32 {
let scale = 10f32.powi(places as i32);
(value * scale).round() / scale
}
#[derive(Serialize)]
pub struct InteractionRecord {
pub kind: String,
pub chain_a: String,
pub resi_a: i32,
pub icode_a: Option<char>,
pub resn_a: String,
pub atoms_a: String,
pub chain_b: String,
pub resi_b: i32,
pub icode_b: Option<char>,
pub resn_b: String,
pub atoms_b: String,
pub distance: f32,
pub angle: Option<f32>,
}
impl Row for InteractionRecord {
fn columns() -> Vec<&'static str> {
vec![
"kind", "chain_a", "resi_a", "icode_a", "resn_a", "atoms_a", "chain_b", "resi_b",
"icode_b", "resn_b", "atoms_b", "distance", "angle",
]
}
fn cells(&self) -> Vec<String> {
vec![
self.kind.clone(),
self.chain_a.clone(),
self.resi_a.to_string(),
code(self.icode_a),
self.resn_a.clone(),
self.atoms_a.clone(),
self.chain_b.clone(),
self.resi_b.to_string(),
code(self.icode_b),
self.resn_b.clone(),
self.atoms_b.clone(),
format!("{:.2}", self.distance),
self.angle.map_or_else(String::new, |a| format!("{a:.1}")),
]
}
}
pub fn selected(
protein: &Protein,
chosen: &AtomSet,
kinds: &[InteractionKind],
) -> Vec<Interaction> {
detect(protein)
.into_iter()
.filter(|found| kinds.is_empty() || kinds.contains(&found.kind))
.filter(|found| touches(found, chosen))
.collect()
}
pub fn interactions(
protein: &Protein,
chosen: &AtomSet,
kinds: &[InteractionKind],
) -> Vec<InteractionRecord> {
let mut records: Vec<InteractionRecord> = selected(protein, chosen, kinds)
.iter()
.map(|found| record(protein, found))
.collect();
records.sort_by(|a, b| {
(
&a.kind, &a.chain_a, a.resi_a, a.icode_a, &a.chain_b, a.resi_b, a.icode_b,
)
.cmp(&(
&b.kind, &b.chain_a, b.resi_a, b.icode_a, &b.chain_b, b.resi_b, b.icode_b,
))
});
records
}
fn touches(interaction: &Interaction, chosen: &AtomSet) -> bool {
interaction
.atoms_a
.iter()
.chain(&interaction.atoms_b)
.any(|&atom| chosen.contains(atom))
}
fn record(protein: &Protein, interaction: &Interaction) -> InteractionRecord {
let side = |atoms: &[usize]| {
let first = &protein.atoms[atoms[0]];
let names: Vec<&str> = atoms
.iter()
.map(|&i| protein.atoms[i].name.as_str())
.collect();
(
first.chain_id.as_str().to_string(),
first.residue_seq,
first.insertion_code,
first.residue_name.as_str().to_string(),
names.join("+"),
)
};
let (chain_a, resi_a, icode_a, resn_a, atoms_a) = side(&interaction.atoms_a);
let (chain_b, resi_b, icode_b, resn_b, atoms_b) = side(&interaction.atoms_b);
InteractionRecord {
kind: interaction.kind.label().to_string(),
chain_a,
resi_a,
icode_a,
resn_a,
atoms_a,
chain_b,
resi_b,
icode_b,
resn_b,
atoms_b,
distance: rounded(interaction.distance, 2),
angle: interaction.angle.map(|angle| rounded(angle, 1)),
}
}
#[derive(Serialize)]
pub struct SecondaryRecord {
pub chain: String,
pub resi: i32,
pub icode: Option<char>,
pub resn: String,
pub ss: char,
}
impl Row for SecondaryRecord {
fn columns() -> Vec<&'static str> {
vec!["chain", "resi", "icode", "resn", "ss"]
}
fn cells(&self) -> Vec<String> {
vec![
self.chain.clone(),
self.resi.to_string(),
code(self.icode),
self.resn.clone(),
self.ss.to_string(),
]
}
}
pub fn secondary(protein: &Protein, chosen: &AtomSet) -> Vec<SecondaryRecord> {
residues(protein, chosen)
.map(|(range, first)| {
let anchor = range
.clone()
.find(|&i| protein.atoms[i].name == "CA")
.unwrap_or(range.start);
SecondaryRecord {
chain: first.chain_id.as_str().to_string(),
resi: first.residue_seq,
icode: first.insertion_code,
resn: first.residue_name.as_str().to_string(),
ss: protein.atoms[anchor].secondary_structure.code(),
}
})
.collect()
}
#[derive(Serialize)]
pub struct SasaRecord {
pub chain: String,
pub resi: i32,
pub icode: Option<char>,
pub resn: String,
pub sasa: f32,
pub rsa: Option<f32>,
}
impl Row for SasaRecord {
fn columns() -> Vec<&'static str> {
vec!["chain", "resi", "icode", "resn", "sasa", "rsa"]
}
fn cells(&self) -> Vec<String> {
vec![
self.chain.clone(),
self.resi.to_string(),
code(self.icode),
self.resn.clone(),
format!("{:.2}", self.sasa),
self.rsa.map_or(String::new(), |rsa| format!("{rsa:.3}")),
]
}
}
pub fn sasa(protein: &Protein, chosen: &AtomSet) -> Vec<SasaRecord> {
let surface: Vec<usize> = (0..protein.atoms.len())
.filter(|&i| bears_surface(&protein.atoms[i]))
.collect();
let atoms: Vec<Atom> = surface.iter().map(|&i| protein.atoms[i].clone()).collect();
let computed = SurfaceCalculator::default().calculate_atom_sasa(&atoms);
let mut areas = vec![0.0f32; protein.atoms.len()];
for (slot, &atom) in surface.iter().enumerate() {
areas[atom] = computed.get(slot).copied().unwrap_or(0.0);
}
let has_surface =
|range: &std::ops::Range<usize>| range.clone().any(|i| bears_surface(&protein.atoms[i]));
residues(protein, chosen)
.filter(|(range, _)| has_surface(range))
.map(|(range, first)| {
let resn = first.residue_name.as_str().to_string();
let absolute: f32 = range.map(|i| areas.get(i).copied().unwrap_or(0.0)).sum();
let rsa = relative_sasa(absolute, &resn).map(|value| rounded(value, 3));
SasaRecord {
chain: first.chain_id.as_str().to_string(),
resi: first.residue_seq,
icode: first.insertion_code,
resn,
sasa: rounded(absolute, 2),
rsa,
}
})
.collect()
}
fn bears_surface(atom: &Atom) -> bool {
atom.is_polymer() && !atom.element.as_str().eq_ignore_ascii_case("H")
}
fn residues<'a>(
protein: &'a Protein,
chosen: &'a AtomSet,
) -> impl Iterator<Item = (std::ops::Range<usize>, &'a Atom)> + 'a {
let key = |atom: &Atom| (atom.chain_id, atom.residue_seq, atom.insertion_code);
let mut index = 0;
std::iter::from_fn(move || {
while index < protein.atoms.len() {
let start = index;
let current = key(&protein.atoms[start]);
while index < protein.atoms.len() && key(&protein.atoms[index]) == current {
index += 1;
}
let range = start..index;
if range.clone().any(|i| chosen.contains(i)) {
return Some((range, &protein.atoms[start]));
}
}
None
})
}
#[cfg(test)]
mod tests {
use glam::Vec3;
use pixelfold_core::{FixedStr, Molecule, SecondaryStructure, select};
use super::*;
fn atom(element: &str, residue: &str, seq: i32, molecule: Molecule, x: f32) -> Atom {
Atom {
serial: 0,
name: FixedStr::new(element),
element: FixedStr::new(element),
residue_name: FixedStr::new(residue),
residue_seq: seq,
chain_id: FixedStr::new("A"),
is_hetatm: residue != "ALA",
molecule,
altloc: None,
occupancy: 1.0,
insertion_code: None,
model_number: 1,
position: Vec3::new(x, 0.0, 0.0),
b_factor: 0.0,
secondary_structure: SecondaryStructure::Coil,
}
}
fn report(atoms: Vec<Atom>) -> Vec<SasaRecord> {
let protein = Protein {
atoms,
title: String::new(),
hbonds: Vec::new(),
assembly: None,
components: Default::default(),
};
let all = select("all", &protein).expect("`all` always parses");
sasa(&protein, &all)
}
fn area(records: &[SasaRecord], resn: &str) -> Option<f32> {
records.iter().find(|r| r.resn == resn).map(|r| r.sasa)
}
fn reported(records: &[SasaRecord], resn: &str) -> f32 {
area(records, resn).unwrap_or_else(|| panic!("{resn} is reported"))
}
#[test]
fn sasa_keeps_modified_residues_and_drops_ligands() {
let alanine = atom("C", "ALA", 1, Molecule::Protein, 0.0);
let selenomethionine = atom("SE", "MSE", 2, Molecule::Protein, 3.0);
let glycerol = atom("C", "GOL", 3, Molecule::NonPolymer, -1.0);
let alone = report(vec![alanine.clone()]);
let records = report(vec![alanine.clone(), selenomethionine.clone()]);
let with_ligand = report(vec![alanine, selenomethionine, glycerol]);
assert!(reported(&records, "MSE") > 0.0);
assert!(reported(&records, "ALA") < reported(&alone, "ALA"));
assert_eq!(area(&with_ligand, "GOL"), None);
assert_eq!(reported(&with_ligand, "ALA"), reported(&records, "ALA"));
}
}