molar_ff 2.4.3

GAFF/GAFF2 atom typing, partial charges, and Amber mechanics and minimization for MolAR
Documentation
//! Force-field atom typing, partial charges, and Amber mechanics for MolAR.
//!
//! This crate assigns GAFF and GAFF2 atom types to a molecule. Typing is
//! exposed through the [`ApplyFF`] trait, which is blanket-implemented for every MolAR
//! object that exposes atoms and bonds — [`System`], [`Topology`], and the bound
//! selection types.
//!
//! ```no_run
//! use molar::prelude::*;
//! use molar_ff::{ApplyFF, FFType};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut sys = System::from_file("ligand.sdf")?;
//! sys.apply_ff(FFType::Gaff)?;                                  // whole system
//! sys.select_bound_mut("resname LIG")?.apply_ff(FFType::Gaff)?; // just a selection
//! # Ok(())
//! # }
//! ```
//!
//! # Input requirement
//! Molecules must already carry bond orders (SDF/mol2). Inputs without bond orders
//! (PDB/GRO) return [`FFError::MissingBondOrders`] — [`ApplyFF`] does not perceive bond orders
//! itself. To type such an input, run the opt-in [`PrepareForFF::prepare_for_ff`] first: it
//! perceives connectivity, bond orders, charges, and (optionally) hydrogens, then the strict
//! typing/charging operations apply.
//!
//! [`amber::BondedModel`] assigns bonded parameters automatically and evaluates
//! Amber bond, angle, proper, and improper energies and analytic forces. Missing
//! parameters use bundled Amber correspondence rules; unresolved terms are errors.
//! [`amber::AmberModel`] adds cutoff LJ/Coulomb interactions and an L-BFGS optimizer.

use std::collections::HashMap;

use molar::prelude::*;

mod gaff;
mod prepare;

pub mod charge;
pub mod amber;

pub use prepare::{PrepareForFF, PrepareOptions};

/// The force field whose atom types should be assigned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FFType {
    /// General Amber Force Field (GAFF, `gaff.dat` / `ATOMTYPE_GFF.DEF`).
    Gaff,
    /// General Amber Force Field 2 (GAFF2, `gaff2.dat` / `ATOMTYPE_GFF2.DEF`).
    Gaff2,
}

/// Errors returned by [`ApplyFF::apply_ff`].
#[derive(Debug, thiserror::Error)]
pub enum FFError {
    /// A bond in scope has no known order. Force-field typing requires known bond
    /// orders; supply an SDF/mol2 input (this crate does not perceive bond orders).
    #[error(
        "bond {0}-{1} has no known order; force-field typing requires known bond \
         orders (use an SDF/mol2 input)"
    )]
    MissingBondOrders(usize, usize),

    /// The selection is not bond-complete: a selected atom is bonded to an atom
    /// outside the selection, so it cannot be typed as a whole molecule.
    #[error(
        "selection is not bond-complete: atom {global} is bonded to non-selected \
         atom {neighbor}"
    )]
    OpenSelection { global: usize, neighbor: usize },

    /// The aromatic bonds in scope describe no valid molecule: an aromatic system has no Kekulé
    /// structure, or an atom is over-valent. GAFF would still assign types to such input, but
    /// they would be wrong without any sign of it (an indole N with its N-H lost types as `n2`,
    /// not `na`), so it is refused — the same input [`ApplyCharges`] rejects.
    #[error(transparent)]
    InvalidAromatic(molar::KekulizeError),

    /// No matching rule assigned a type to this atom.
    #[error("could not assign a {ff:?} atom type to atom {local} (element Z={z})")]
    UntypedAtom { ff: FFType, local: usize, z: u8 },
}

/// Assign force-field atom types, writing the result into each atom's `type_name`.
///
/// Blanket-implemented for every type that can both read atoms + bonds and write atoms
/// ([`AtomMutProvider`] + [`BondProvider`]): [`System`], [`Topology`], and the mutable
/// bound selection types. A bare detached [`Sel`] does not qualify — bind it first
/// (e.g. `sys.try_bind_mut(&sel)`).
///
/// The object is treated as **the molecule**: perception (rings/aromaticity/conjugation)
/// runs over the atoms in scope using only bonds whose both endpoints are in scope. For
/// a whole [`System`] this is the entire topology; for a selection it is the selected
/// atoms (which should form complete molecule(s) — see [`FFError::OpenSelection`]).
pub trait ApplyFF {
    fn apply_ff(&mut self, ff: FFType) -> Result<(), FFError>;
}

impl<T: AtomMutProvider + BondProvider> ApplyFF for T {
    fn apply_ff(&mut self, ff: FFType) -> Result<(), FFError> {
        // 1. Build a global -> local index map. For `System`/`Topology` this is the
        //    identity (0..n); for a bound selection it maps the sorted global indices.
        let global: Vec<usize> = self.iter_index().collect();
        let g2l: HashMap<usize, usize> =
            global.iter().enumerate().map(|(l, &g)| (g, l)).collect();

        // 2. Local atoms (atomic numbers) in local (== ascending-global) order.
        let z: Vec<u8> = self.iter_atoms().map(|a| a.get_atomic_number()).collect();

        // 3. Local bonds: keep only bonds whose both endpoints are in scope, remapped
        //    to local indices; error on unknown orders and boundary-crossing bonds.
        let mut bonds: Vec<gaff::LocalBond> = Vec::new();
        let mut orders: Vec<BondOrder> = Vec::new();
        for b in self.iter_bonds() {
            let ([g1, g2], b_order) = (b.pair(), b.order());
            match (g2l.get(&g1).copied(), g2l.get(&g2).copied()) {
                (Some(i), Some(j)) => {
                    let order =
                        bond_order_code(b_order).ok_or(FFError::MissingBondOrders(g1, g2))?;
                    bonds.push(gaff::LocalBond { i, j, order });
                    orders.push(b_order);
                }
                (Some(_), None) => {
                    return Err(FFError::OpenSelection { global: g1, neighbor: g2 })
                }
                (None, Some(_)) => {
                    return Err(FFError::OpenSelection { global: g2, neighbor: g1 })
                }
                (None, None) => {} // bond belongs to another molecule; ignore
            }
        }

        // 4. Typing reads aromatic orders as they are, but only a structure that has a Kekulé
        //    form is chemically valid. An element with no known valence, or a search that ran
        //    out of budget, proves nothing wrong, so those still type.
        if orders.contains(&BondOrder::Aromatic) {
            let adj = BondAdjacency::build(z.len(), bonds.iter().map(|b| [b.i, b.j]));
            let fc: Vec<i32> = self
                .iter_atoms()
                .map(|a| a.get_formal_charge().unwrap_or(0))
                .collect();
            match kekulize(&z, &fc, &orders, &adj) {
                Err(
                    e @ (molar::KekulizeError::NonKekulizable(_)
                    | molar::KekulizeError::OverValent(_)),
                ) => {
                    return Err(FFError::InvalidAromatic(e.remap_atoms(&global)));
                }
                _ => {}
            }
        }

        // 5. Compute the types on the local subgraph.
        let types = gaff::gaff_types(&z, &bonds, ff)?;

        // 6. Write results back in local order.
        for (mut a, t) in self.iter_atoms_mut().zip(types) {
            a.set_type_name(&t);
        }
        Ok(())
    }
}

/// Map a MolAR [`BondOrder`] to the integer bond-type code used by the typing engine
/// (1 single, 2 double, 3 triple, 4 aromatic). `Unspecified` yields `None`
/// (→ [`FFError::MissingBondOrders`]).
fn bond_order_code(o: BondOrder) -> Option<u8> {
    match o {
        BondOrder::Single => Some(1),
        BondOrder::Double => Some(2),
        BondOrder::Triple => Some(3),
        BondOrder::Aromatic => Some(4),
        BondOrder::Unspecified => None,
    }
}

/// The partial-charge model used by [`ApplyCharges::apply_charges`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChargeModel {
    /// Espaloma-charge GNN. Charges are equilibrated to sum to the **total formal charge**
    /// of the atoms in scope (Espaloma's whole-graph convention does not split by fragment),
    /// so a cation sums to +1 and an anion to −1.
    ///
    /// Featurized from a Kekulé structure; aromatic-order bonds in scope are kekulized on the
    /// way in (see [`kekulize`]), so the resonance form used is arbitrary but valid.
    Espaloma,
}

/// Errors returned by [`ApplyCharges::apply_charges`].
#[derive(Debug, thiserror::Error)]
pub enum ChargeError {
    /// A bond in scope has no order at all. Charge prediction needs real bond orders, so an
    /// order-less input (PDB/GRO) is rejected; aromatic orders are *not* — they are kekulized.
    #[error(
        "bond {0}-{1} has no known order; charge prediction requires real bond orders \
         (use an SDF/mol2 input)"
    )]
    MissingBondOrders(usize, usize),

    /// Aromatic bonds in scope could not be resolved into a Kekulé structure.
    #[error(transparent)]
    Kekulize(#[from] molar::KekulizeError),

    /// A selected atom is bonded to an atom outside the selection, so the scope is not a
    /// complete molecule and cannot be charged as one.
    #[error(
        "selection is not bond-complete: atom {global} is bonded to non-selected atom {neighbor}"
    )]
    OpenSelection { global: usize, neighbor: usize },

    /// The molecule contains an element the charge model was not trained on.
    #[error("element Z={0} is not supported by the {1:?} charge model")]
    UnsupportedElement(u8, ChargeModel),

    /// The fixed model received inconsistent internal input dimensions.
    #[error("charge model inference failed: {0}")]
    Inference(String),
}

/// Assign partial charges, writing the result into each atom's `charge`.
///
/// Blanket-implemented for every type that can read atoms + bonds and write atoms
/// ([`AtomMutProvider`] + [`BondProvider`]): [`System`], [`Topology`], and the mutable bound
/// selection types — exactly like [`ApplyFF`]. The object in scope is treated as **the
/// molecule** (perception runs over the atoms in scope using only bonds whose endpoints are both
/// in scope); a selection should be bond-complete (see [`ChargeError::OpenSelection`]).
///
/// Each atom's integer formal charge (e.g. read from an SDF `M  CHG` record) is consumed as
/// input to the featurization and then **overwritten** with the predicted partial charge. Their
/// sum is preserved: the equilibration constrains `Σ q_i` to the molecule's total formal charge,
/// so charging a protonated amine yields partial charges summing to +1.
///
/// ```no_run
/// use molar::prelude::*;
/// use molar_ff::{ApplyCharges, ChargeModel};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut sys = System::from_file("ligand.sdf")?;
/// sys.apply_charges(ChargeModel::Espaloma)?;
/// # Ok(())
/// # }
/// ```
pub trait ApplyCharges {
    fn apply_charges(&mut self, model: ChargeModel) -> Result<(), ChargeError>;
}

impl<T: AtomMutProvider + BondProvider> ApplyCharges for T {
    fn apply_charges(&mut self, model: ChargeModel) -> Result<(), ChargeError> {
        match model {
            ChargeModel::Espaloma => {}
        }

        // 1. global -> local index map (identity for System/Topology; sorted globals for a sel).
        let global: Vec<usize> = self.iter_index().collect();
        let g2l: HashMap<usize, usize> =
            global.iter().enumerate().map(|(l, &g)| (g, l)).collect();

        // 2. Atomic numbers + integer formal charges in local order.
        let z: Vec<u8> = self.iter_atoms().map(|a| a.get_atomic_number()).collect();
        if let Some(&bad) = z.iter().find(|&&zi| {
            !matches!(zi, 1 | 6 | 7 | 8 | 9 | 15 | 16 | 17 | 35 | 53)
        }) {
            return Err(ChargeError::UnsupportedElement(bad, model));
        }
        let fc: Vec<i32> = self.iter_atoms().map(|a| a.get_formal_charge().unwrap_or(0)).collect();

        // 3. Local bonds; error on boundary-crossing or order-less bonds.
        let mut pairs: Vec<[usize; 2]> = Vec::new();
        let mut orders: Vec<BondOrder> = Vec::new();
        for b in self.iter_bonds() {
            let ([g1, g2], b_order) = (b.pair(), b.order());
            match (g2l.get(&g1).copied(), g2l.get(&g2).copied()) {
                (Some(i), Some(j)) => {
                    if b_order == BondOrder::Unspecified {
                        return Err(ChargeError::MissingBondOrders(g1, g2));
                    }
                    pairs.push([i, j]);
                    orders.push(b_order);
                }
                (Some(_), None) => {
                    return Err(ChargeError::OpenSelection { global: g1, neighbor: g2 })
                }
                (None, Some(_)) => {
                    return Err(ChargeError::OpenSelection { global: g2, neighbor: g1 })
                }
                (None, None) => {}
            }
        }

        // Espaloma is featurized from a Kekulé structure, so aromatic orders are resolved rather
        // than refused: an SDF order-4 record, or a system already run through
        // `System::perceive`, is charged like any other. A Kekulé input kekulizes to itself, so
        // this changes nothing for the common case.
        let orders = kekulize(&z, &fc, &orders, &BondAdjacency::build(z.len(), pairs.iter().copied()))
            .map_err(|e| ChargeError::Kekulize(e.remap_atoms(&global)))?;
        let bonds: Vec<gaff::LocalBond> = pairs
            .iter()
            .zip(&orders)
            .map(|(&[i, j], &o)| gaff::LocalBond {
                i,
                j,
                order: match o {
                    BondOrder::Double => 2,
                    BondOrder::Triple => 3,
                    _ => 1,
                },
            })
            .collect();

        // 4. Predict, then write the partial charges back in local order.
        let q = charge::espaloma_charges(&z, &fc, &bonds)
            .map_err(|e| ChargeError::Inference(e.to_string()))?;
        for (mut a, c) in self.iter_atoms_mut().zip(q) {
            a.set_charge(c as Float);
        }
        Ok(())
    }
}