molar_ff/lib.rs
1//! Force-field atom typing, partial charges, and Amber mechanics for MolAR.
2//!
3//! This crate assigns GAFF and GAFF2 atom types to a molecule. Typing is
4//! exposed through the [`ApplyFF`] trait, which is blanket-implemented for every MolAR
5//! object that exposes atoms and bonds — [`System`], [`Topology`], and the bound
6//! selection types.
7//!
8//! ```no_run
9//! use molar::prelude::*;
10//! use molar_ff::{ApplyFF, FFType};
11//!
12//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
13//! let mut sys = System::from_file("ligand.sdf")?;
14//! sys.apply_ff(FFType::Gaff)?; // whole system
15//! sys.select_bound_mut("resname LIG")?.apply_ff(FFType::Gaff)?; // just a selection
16//! # Ok(())
17//! # }
18//! ```
19//!
20//! # Input requirement
21//! Molecules must already carry bond orders (SDF/mol2). Inputs without bond orders
22//! (PDB/GRO) return [`FFError::MissingBondOrders`] — [`ApplyFF`] does not perceive bond orders
23//! itself. To type such an input, run the opt-in [`PrepareForFF::prepare_for_ff`] first: it
24//! perceives connectivity, bond orders, charges, and (optionally) hydrogens, then the strict
25//! typing/charging operations apply.
26//!
27//! [`amber::BondedModel`] assigns bonded parameters automatically and evaluates
28//! Amber bond, angle, proper, and improper energies and analytic forces. Missing
29//! parameters use bundled Amber correspondence rules; unresolved terms are errors.
30//! [`amber::AmberModel`] adds cutoff LJ/Coulomb interactions and an L-BFGS optimizer.
31
32use std::collections::HashMap;
33
34use molar::prelude::*;
35
36mod gaff;
37mod prepare;
38
39pub mod charge;
40pub mod amber;
41
42pub use prepare::{PrepareForFF, PrepareOptions};
43
44/// The force field whose atom types should be assigned.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum FFType {
47 /// General Amber Force Field (GAFF, `gaff.dat` / `ATOMTYPE_GFF.DEF`).
48 Gaff,
49 /// General Amber Force Field 2 (GAFF2, `gaff2.dat` / `ATOMTYPE_GFF2.DEF`).
50 Gaff2,
51}
52
53/// Errors returned by [`ApplyFF::apply_ff`].
54#[derive(Debug, thiserror::Error)]
55pub enum FFError {
56 /// A bond in scope has no known order. Force-field typing requires known bond
57 /// orders; supply an SDF/mol2 input (this crate does not perceive bond orders).
58 #[error(
59 "bond {0}-{1} has no known order; force-field typing requires known bond \
60 orders (use an SDF/mol2 input)"
61 )]
62 MissingBondOrders(usize, usize),
63
64 /// The selection is not bond-complete: a selected atom is bonded to an atom
65 /// outside the selection, so it cannot be typed as a whole molecule.
66 #[error(
67 "selection is not bond-complete: atom {global} is bonded to non-selected \
68 atom {neighbor}"
69 )]
70 OpenSelection { global: usize, neighbor: usize },
71
72 /// The aromatic bonds in scope describe no valid molecule: an aromatic system has no Kekulé
73 /// structure, or an atom is over-valent. GAFF would still assign types to such input, but
74 /// they would be wrong without any sign of it (an indole N with its N-H lost types as `n2`,
75 /// not `na`), so it is refused — the same input [`ApplyCharges`] rejects.
76 #[error(transparent)]
77 InvalidAromatic(molar::KekulizeError),
78
79 /// No matching rule assigned a type to this atom.
80 #[error("could not assign a {ff:?} atom type to atom {local} (element Z={z})")]
81 UntypedAtom { ff: FFType, local: usize, z: u8 },
82}
83
84/// Assign force-field atom types, writing the result into each atom's `type_name`.
85///
86/// Blanket-implemented for every type that can both read atoms + bonds and write atoms
87/// ([`AtomMutProvider`] + [`BondProvider`]): [`System`], [`Topology`], and the mutable
88/// bound selection types. A bare detached [`Sel`] does not qualify — bind it first
89/// (e.g. `sys.try_bind_mut(&sel)`).
90///
91/// The object is treated as **the molecule**: perception (rings/aromaticity/conjugation)
92/// runs over the atoms in scope using only bonds whose both endpoints are in scope. For
93/// a whole [`System`] this is the entire topology; for a selection it is the selected
94/// atoms (which should form complete molecule(s) — see [`FFError::OpenSelection`]).
95pub trait ApplyFF {
96 fn apply_ff(&mut self, ff: FFType) -> Result<(), FFError>;
97}
98
99impl<T: AtomMutProvider + BondProvider> ApplyFF for T {
100 fn apply_ff(&mut self, ff: FFType) -> Result<(), FFError> {
101 // 1. Build a global -> local index map. For `System`/`Topology` this is the
102 // identity (0..n); for a bound selection it maps the sorted global indices.
103 let global: Vec<usize> = self.iter_index().collect();
104 let g2l: HashMap<usize, usize> =
105 global.iter().enumerate().map(|(l, &g)| (g, l)).collect();
106
107 // 2. Local atoms (atomic numbers) in local (== ascending-global) order.
108 let z: Vec<u8> = self.iter_atoms().map(|a| a.get_atomic_number()).collect();
109
110 // 3. Local bonds: keep only bonds whose both endpoints are in scope, remapped
111 // to local indices; error on unknown orders and boundary-crossing bonds.
112 let mut bonds: Vec<gaff::LocalBond> = Vec::new();
113 let mut orders: Vec<BondOrder> = Vec::new();
114 for b in self.iter_bonds() {
115 let ([g1, g2], b_order) = (b.pair(), b.order());
116 match (g2l.get(&g1).copied(), g2l.get(&g2).copied()) {
117 (Some(i), Some(j)) => {
118 let order =
119 bond_order_code(b_order).ok_or(FFError::MissingBondOrders(g1, g2))?;
120 bonds.push(gaff::LocalBond { i, j, order });
121 orders.push(b_order);
122 }
123 (Some(_), None) => {
124 return Err(FFError::OpenSelection { global: g1, neighbor: g2 })
125 }
126 (None, Some(_)) => {
127 return Err(FFError::OpenSelection { global: g2, neighbor: g1 })
128 }
129 (None, None) => {} // bond belongs to another molecule; ignore
130 }
131 }
132
133 // 4. Typing reads aromatic orders as they are, but only a structure that has a Kekulé
134 // form is chemically valid. An element with no known valence, or a search that ran
135 // out of budget, proves nothing wrong, so those still type.
136 if orders.contains(&BondOrder::Aromatic) {
137 let adj = BondAdjacency::build(z.len(), bonds.iter().map(|b| [b.i, b.j]));
138 let fc: Vec<i32> = self
139 .iter_atoms()
140 .map(|a| a.get_formal_charge().unwrap_or(0))
141 .collect();
142 match kekulize(&z, &fc, &orders, &adj) {
143 Err(
144 e @ (molar::KekulizeError::NonKekulizable(_)
145 | molar::KekulizeError::OverValent(_)),
146 ) => {
147 return Err(FFError::InvalidAromatic(e.remap_atoms(&global)));
148 }
149 _ => {}
150 }
151 }
152
153 // 5. Compute the types on the local subgraph.
154 let types = gaff::gaff_types(&z, &bonds, ff)?;
155
156 // 6. Write results back in local order.
157 for (mut a, t) in self.iter_atoms_mut().zip(types) {
158 a.set_type_name(&t);
159 }
160 Ok(())
161 }
162}
163
164/// Map a MolAR [`BondOrder`] to the integer bond-type code used by the typing engine
165/// (1 single, 2 double, 3 triple, 4 aromatic). `Unspecified` yields `None`
166/// (→ [`FFError::MissingBondOrders`]).
167fn bond_order_code(o: BondOrder) -> Option<u8> {
168 match o {
169 BondOrder::Single => Some(1),
170 BondOrder::Double => Some(2),
171 BondOrder::Triple => Some(3),
172 BondOrder::Aromatic => Some(4),
173 BondOrder::Unspecified => None,
174 }
175}
176
177/// The partial-charge model used by [`ApplyCharges::apply_charges`].
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub enum ChargeModel {
180 /// Espaloma-charge GNN. Charges are equilibrated to sum to the **total formal charge**
181 /// of the atoms in scope (Espaloma's whole-graph convention does not split by fragment),
182 /// so a cation sums to +1 and an anion to −1.
183 ///
184 /// Featurized from a Kekulé structure; aromatic-order bonds in scope are kekulized on the
185 /// way in (see [`kekulize`]), so the resonance form used is arbitrary but valid.
186 Espaloma,
187}
188
189/// Errors returned by [`ApplyCharges::apply_charges`].
190#[derive(Debug, thiserror::Error)]
191pub enum ChargeError {
192 /// A bond in scope has no order at all. Charge prediction needs real bond orders, so an
193 /// order-less input (PDB/GRO) is rejected; aromatic orders are *not* — they are kekulized.
194 #[error(
195 "bond {0}-{1} has no known order; charge prediction requires real bond orders \
196 (use an SDF/mol2 input)"
197 )]
198 MissingBondOrders(usize, usize),
199
200 /// Aromatic bonds in scope could not be resolved into a Kekulé structure.
201 #[error(transparent)]
202 Kekulize(#[from] molar::KekulizeError),
203
204 /// A selected atom is bonded to an atom outside the selection, so the scope is not a
205 /// complete molecule and cannot be charged as one.
206 #[error(
207 "selection is not bond-complete: atom {global} is bonded to non-selected atom {neighbor}"
208 )]
209 OpenSelection { global: usize, neighbor: usize },
210
211 /// The molecule contains an element the charge model was not trained on.
212 #[error("element Z={0} is not supported by the {1:?} charge model")]
213 UnsupportedElement(u8, ChargeModel),
214
215 /// The fixed model received inconsistent internal input dimensions.
216 #[error("charge model inference failed: {0}")]
217 Inference(String),
218}
219
220/// Assign partial charges, writing the result into each atom's `charge`.
221///
222/// Blanket-implemented for every type that can read atoms + bonds and write atoms
223/// ([`AtomMutProvider`] + [`BondProvider`]): [`System`], [`Topology`], and the mutable bound
224/// selection types — exactly like [`ApplyFF`]. The object in scope is treated as **the
225/// molecule** (perception runs over the atoms in scope using only bonds whose endpoints are both
226/// in scope); a selection should be bond-complete (see [`ChargeError::OpenSelection`]).
227///
228/// Each atom's integer formal charge (e.g. read from an SDF `M CHG` record) is consumed as
229/// input to the featurization and then **overwritten** with the predicted partial charge. Their
230/// sum is preserved: the equilibration constrains `Σ q_i` to the molecule's total formal charge,
231/// so charging a protonated amine yields partial charges summing to +1.
232///
233/// ```no_run
234/// use molar::prelude::*;
235/// use molar_ff::{ApplyCharges, ChargeModel};
236///
237/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
238/// let mut sys = System::from_file("ligand.sdf")?;
239/// sys.apply_charges(ChargeModel::Espaloma)?;
240/// # Ok(())
241/// # }
242/// ```
243pub trait ApplyCharges {
244 fn apply_charges(&mut self, model: ChargeModel) -> Result<(), ChargeError>;
245}
246
247impl<T: AtomMutProvider + BondProvider> ApplyCharges for T {
248 fn apply_charges(&mut self, model: ChargeModel) -> Result<(), ChargeError> {
249 match model {
250 ChargeModel::Espaloma => {}
251 }
252
253 // 1. global -> local index map (identity for System/Topology; sorted globals for a sel).
254 let global: Vec<usize> = self.iter_index().collect();
255 let g2l: HashMap<usize, usize> =
256 global.iter().enumerate().map(|(l, &g)| (g, l)).collect();
257
258 // 2. Atomic numbers + integer formal charges in local order.
259 let z: Vec<u8> = self.iter_atoms().map(|a| a.get_atomic_number()).collect();
260 if let Some(&bad) = z.iter().find(|&&zi| {
261 !matches!(zi, 1 | 6 | 7 | 8 | 9 | 15 | 16 | 17 | 35 | 53)
262 }) {
263 return Err(ChargeError::UnsupportedElement(bad, model));
264 }
265 let fc: Vec<i32> = self.iter_atoms().map(|a| a.get_formal_charge().unwrap_or(0)).collect();
266
267 // 3. Local bonds; error on boundary-crossing or order-less bonds.
268 let mut pairs: Vec<[usize; 2]> = Vec::new();
269 let mut orders: Vec<BondOrder> = Vec::new();
270 for b in self.iter_bonds() {
271 let ([g1, g2], b_order) = (b.pair(), b.order());
272 match (g2l.get(&g1).copied(), g2l.get(&g2).copied()) {
273 (Some(i), Some(j)) => {
274 if b_order == BondOrder::Unspecified {
275 return Err(ChargeError::MissingBondOrders(g1, g2));
276 }
277 pairs.push([i, j]);
278 orders.push(b_order);
279 }
280 (Some(_), None) => {
281 return Err(ChargeError::OpenSelection { global: g1, neighbor: g2 })
282 }
283 (None, Some(_)) => {
284 return Err(ChargeError::OpenSelection { global: g2, neighbor: g1 })
285 }
286 (None, None) => {}
287 }
288 }
289
290 // Espaloma is featurized from a Kekulé structure, so aromatic orders are resolved rather
291 // than refused: an SDF order-4 record, or a system already run through
292 // `System::perceive`, is charged like any other. A Kekulé input kekulizes to itself, so
293 // this changes nothing for the common case.
294 let orders = kekulize(&z, &fc, &orders, &BondAdjacency::build(z.len(), pairs.iter().copied()))
295 .map_err(|e| ChargeError::Kekulize(e.remap_atoms(&global)))?;
296 let bonds: Vec<gaff::LocalBond> = pairs
297 .iter()
298 .zip(&orders)
299 .map(|(&[i, j], &o)| gaff::LocalBond {
300 i,
301 j,
302 order: match o {
303 BondOrder::Double => 2,
304 BondOrder::Triple => 3,
305 _ => 1,
306 },
307 })
308 .collect();
309
310 // 4. Predict, then write the partial charges back in local order.
311 let q = charge::espaloma_charges(&z, &fc, &bonds)
312 .map_err(|e| ChargeError::Inference(e.to_string()))?;
313 for (mut a, c) in self.iter_atoms_mut().zip(q) {
314 a.set_charge(c as Float);
315 }
316 Ok(())
317 }
318}