cosmolkit-core 0.2.1

Redesigned COSMolKit core with value-style molecule state and explicit topology operation contracts
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
// RDKit marker convention defined in dev/source_reproduction_protocol.md.
//
// Port of RDKit MolOps fragmentation functions from:
//   third_party/rdkit/Code/GraphMol/MolOps.cpp
//
// The C++ source uses boost::connected_components for graph connectivity.
// Here we implement an equivalent DFS-based connected-components algorithm.

use crate::{
    AdjacencyList, Atom, AtomSpec, Bond, BondSpec, Molecule, MoleculeBuilder,
    error::MoleculeBuildError,
};

// ---------------------------------------------------------------------------
// FragmentError
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum FragmentError {
    #[error("molecule has no atoms")]
    EmptyMolecule,
    #[error("failed to build fragment molecule: {0}")]
    BuildError(#[from] MoleculeBuildError),
}

// ---------------------------------------------------------------------------
// find_connected_components — DFS-based graph traversal
//
// RDKit equivalent: boost::connected_components (used in getMolFrags)
// RDKit source: MolOps.cpp lines 852-857
// RDKit✔️✔️: unsigned int getMolFrags(const ROMol &mol, INT_VECT &mapping) {
// RDKit✔️✔️:   unsigned int natms = mol.getNumAtoms();
// RDKit✔️✔️:   mapping.resize(natms);
// RDKit✔️✔️:   return natms ? boost::connected_components(mol.getTopology(), &mapping[0])
// RDKit✔️✔️:                : 0;
// RDKit✔️✔️: };
//
// Boost connected_components assigns a component ID to each vertex.
// We re-implement with iterative DFS over CSR adjacency.
// ---------------------------------------------------------------------------
fn find_connected_components(mol: &Molecule) -> Vec<usize> {
    let num_atoms = mol.num_atoms();
    if num_atoms == 0 {
        return Vec::new();
    }

    // Build adjacency from bonds (like boost does from the graph topology)
    let adjacency = AdjacencyList::from_topology(num_atoms, mol.bonds());

    // RDKit (line 854): mapping.resize(natms);
    let mut component_of = vec![usize::MAX; num_atoms];
    let mut next_component: usize = 0;

    for start in 0..num_atoms {
        if component_of[start] != usize::MAX {
            continue;
        }

        // Iterative DFS (stack-based) — equivalent to boost's BFS traversal
        let mut stack: Vec<usize> = Vec::new();
        stack.push(start);
        component_of[start] = next_component;

        while let Some(atom_idx) = stack.pop() {
            for neighbor_ref in adjacency.neighbors_of(atom_idx) {
                let nbr = neighbor_ref.atom_index;
                if component_of[nbr] == usize::MAX {
                    component_of[nbr] = next_component;
                    stack.push(nbr);
                }
            }
        }

        next_component += 1;
    }

    component_of
}

// ---------------------------------------------------------------------------
// get_fragment_atom_mapping
//
// RDKit equivalent: getMolFrags(mol, mapping) returning frag assignment per atom
// RDKit source: MolOps.cpp lines 852-857
//
// Returns a Vec where index i contains the fragment index for atom i.
// ---------------------------------------------------------------------------
pub fn get_fragment_atom_mapping(mol: &Molecule) -> Vec<usize> {
    find_connected_components(mol)
}

// ---------------------------------------------------------------------------
// get_num_fragments
//
// Counts the number of connected components.
// RDKit equivalent: getMolFrags returning unsigned int count
// RDKit source: MolOps.cpp lines 852-857
// ---------------------------------------------------------------------------
pub fn get_num_fragments(mol: &Molecule) -> usize {
    let component_of = find_connected_components(mol);
    if component_of.is_empty() {
        return 0;
    }
    // The last component ID is one less than the count of unique IDs,
    // because IDs are assigned consecutively starting from 0.
    *component_of.iter().max().unwrap_or(&0) + 1
}

// ---------------------------------------------------------------------------
// group_atoms_by_fragment
//
// RDKit equivalent: getMolFrags(mol, VECT_INT_VECT &frags) — lines 859-878
// RDKit✔️✔️: unsigned int getMolFrags(const ROMol &mol, VECT_INT_VECT &frags) {
// RDKit✔️✔️:   frags.clear();
// RDKit✔️✔️:   INT_VECT mapping;
// RDKit✔️✔️:   getMolFrags(mol, mapping);
// RDKit✔️✔️:   INT_INT_VECT_MAP comMap;
// RDKit✔️✔️:   for (unsigned int i = 0; i < mol.getNumAtoms(); i++) {
// RDKit✔️✔️:     int mi = mapping[i];
// RDKit✔️✔️:     if (comMap.find(mi) == comMap.end()) {
// RDKit✔️✔️:       INT_VECT comp;
// RDKit✔️✔️:       comMap[mi] = comp;
// RDKit✔️✔️:     }
// RDKit✔️✔️:     comMap[mi].push_back(i);
// RDKit✔️✔️:   }
// RDKit✔️✔️:   for (INT_INT_VECT_MAP_CI mci = comMap.begin(); mci != comMap.end(); mci++) {
// RDKit✔️✔️:     frags.push_back((*mci).second);
// RDKit✔️✔️:   }
// RDKit✔️✔️:   return rdcast<unsigned int>(frags.size());
// RDKit✔️✔️: }
// ---------------------------------------------------------------------------
fn group_atoms_by_fragment(mol: &Molecule) -> Vec<Vec<usize>> {
    let component_of = find_connected_components(mol);
    if component_of.is_empty() {
        return Vec::new();
    }

    let num_fragments = get_num_fragments(mol);
    let mut frags: Vec<Vec<usize>> = vec![Vec::new(); num_fragments];
    for (atom_idx, frag_idx) in component_of.into_iter().enumerate() {
        frags[frag_idx].push(atom_idx);
    }
    frags
}

// ---------------------------------------------------------------------------
// Helper: build a Molecule for one fragment from atom indices
//
// RDKit equivalent: the per-fragment molecule construction inside getTheFrags()
// RDKit source: MolOps.cpp lines 725-814
//
// We use MoleculeBuilder to construct a new molecule from the atoms and bonds
// that belong to this fragment.
// ---------------------------------------------------------------------------
fn build_fragment_molecule(
    mol: &Molecule,
    fragment_atoms: &[usize],
    copy_conformers: bool,
) -> Result<Molecule, MoleculeBuildError> {
    let mut builder = MoleculeBuilder::new();

    let num_frag_atoms = fragment_atoms.len();

    // Build old-index -> new-index mapping for atoms in this fragment
    // RDKit equivalent: the atomsInFrag bitset + new atom index tracking
    // RDKit source: MolOps.cpp lines 727-733
    let mut old_to_new = vec![usize::MAX; mol.num_atoms()];
    for (new_idx, old_idx) in fragment_atoms.iter().enumerate() {
        old_to_new[*old_idx] = new_idx;
    }

    // Add each atom to the builder
    // RDKit equivalent: getTheFrags — atoms are either copied via copyMolSubset
    // or implicitly kept when batch-removing non-fragment atoms (lines 801-809).
    // Here we add atoms explicitly.
    for old_idx in fragment_atoms {
        let atom = mol
            .atoms()
            .get(*old_idx)
            .expect("fragment atom index out of range");
        let spec = atom_to_spec(atom);
        builder.add_atom(spec);
    }

    // Add bonds whose both endpoints are in this fragment
    // RDKit equivalent: getTheFrags — after removing atoms, bonds between
    // surviving atoms are kept automatically (lines 804-809).
    for bond in mol.bonds() {
        let begin_old = bond.begin().index();
        let end_old = bond.end().index();
        if old_to_new[begin_old] != usize::MAX && old_to_new[end_old] != usize::MAX {
            let begin_new = AtomId_usize(old_to_new[begin_old]);
            let end_new = AtomId_usize(old_to_new[end_old]);

            // Remap stereo atoms if present
            let stereo_atoms = bond.stereo_atoms().map(|[sa, sb]| {
                (
                    AtomId_usize(old_to_new[sa.index()]),
                    AtomId_usize(old_to_new[sb.index()]),
                )
            });

            let mut spec = BondSpec::new(begin_new, end_new, bond.order())
                .with_aromatic(bond.is_aromatic())
                .with_conjugated(bond.is_conjugated())
                .with_direction(bond.direction())
                .with_stereo(bond.stereo());
            if let Some((sa, sb)) = stereo_atoms {
                spec = spec.with_stereo_atoms(sa, sb);
            }
            // Copy bond properties
            for (key, value) in bond.props() {
                spec = spec.with_prop(key.clone(), value.clone());
            }
            builder.add_bond(spec)?;
        }
    }

    // Copy conformers if requested
    // RDKit equivalent: getTheFrags lines 817-821
    if copy_conformers {
        if let Some(coords_2d) = mol.coords_2d() {
            let frag_coords: Vec<[f64; 2]> = fragment_atoms
                .iter()
                .filter_map(|old_idx| coords_2d.get(*old_idx).copied())
                .collect();
            if frag_coords.len() == num_frag_atoms {
                builder.set_2d_coordinates(frag_coords)?;
            }
        }
        for conformer in mol.conformers_3d() {
            let frag_coords: Vec<[f64; 3]> = fragment_atoms
                .iter()
                .filter_map(|old_idx| conformer.coords().get(*old_idx).copied())
                .collect();
            if frag_coords.len() == num_frag_atoms {
                builder.add_3d_conformer(frag_coords)?;
            }
        }
    }

    builder.build()
}

// ---------------------------------------------------------------------------
// Helper: convert Atom to AtomSpec for building a new molecule
// ---------------------------------------------------------------------------
fn atom_to_spec(atom: &Atom) -> AtomSpec {
    let mut spec = AtomSpec::new(atom.element())
        .with_formal_charge(atom.formal_charge())
        .with_explicit_hydrogens(atom.explicit_hydrogens())
        .with_chiral_tag(atom.chiral_tag())
        .with_aromatic(atom.is_aromatic())
        .with_no_implicit(atom.no_implicit())
        .with_radical_electrons(atom.radical_electrons())
        .with_hybridization(atom.hybridization());
    if let Some(isotope) = atom.isotope() {
        spec = spec.with_isotope(isotope);
    }
    if let Some(atom_map) = atom.atom_map() {
        spec = spec.with_atom_map(atom_map);
    }
    if let Some(chiral_perm) = atom.chiral_permutation() {
        spec = spec.with_chiral_permutation(chiral_perm);
    }
    if atom.unknown_stereo() {
        spec = spec.with_unknown_stereo(true);
    }
    if let Some(mol_parity) = atom.mol_parity() {
        spec = spec.with_mol_parity(mol_parity);
    }
    if let Some(mol_inv) = atom.mol_inversion_flag() {
        spec = spec.with_mol_inversion_flag(mol_inv);
    }
    if atom.implicit_hydrogen() {
        spec = spec.with_implicit_hydrogen(true);
    }
    let tracked: Vec<u16> = atom.tracked_isotopic_hydrogens().to_vec();
    if !tracked.is_empty() {
        spec = spec.with_tracked_isotopic_hydrogens(tracked);
    }
    if let Some(query) = atom.query() {
        spec = spec.with_query(query.clone());
    }
    for (key, value) in atom.props() {
        spec = spec.with_prop(key.clone(), value.clone());
    }
    if let Some(pdb_info) = atom.pdb_residue_info() {
        spec = spec.with_pdb_residue_info(pdb_info.clone());
    }
    spec
}

// ---------------------------------------------------------------------------
// Helper: wrap a usize into AtomId for builder calls
// ---------------------------------------------------------------------------
fn AtomId_usize(index: usize) -> crate::AtomId {
    crate::AtomId::new(index)
}

// ---------------------------------------------------------------------------
// get_mol_frags
//
// Decompose a molecule into its connected components (fragments).
// Returns a list of Molecule, one per fragment.
//
// RDKit equivalent: the molecule-producing overload of getMolFrags
// RDKit source: MolOps.cpp lines 704-835 (getTheFrags) + lines 838-888 (public overloads)
//
// RDKit✔️✔️: std::vector<std::unique_ptr<ROMol>> getTheFrags(
// RDKit✔️✔️:     const ROMol &mol, bool sanitizeFrags, INT_VECT *frags,
// RDKit✔️✔️:     VECT_INT_VECT *fragsMolAtomMapping, bool copyConformers) {
// RDKit✔️✔️:   std::unique_ptr<INT_VECT> mappingStorage;
// RDKit✔️✔️:   if (!frags) {
// RDKit✔️✔️:     mappingStorage.reset(new INT_VECT);
// RDKit✔️✔️:     frags = mappingStorage.get();
// RDKit✔️✔️:   }
// RDKit✔️✔️:   int nFrags = getMolFrags(mol, *frags);
// RDKit✔️✔️:   std::vector<std::unique_ptr<RWMol>> res;
// RDKit✔️✔️:   if (nFrags == 1) {
// RDKit✔️✔️:     res.emplace_back(new RWMol(mol));
// RDKit✔️✔️:     if (fragsMolAtomMapping) {
// RDKit✔️✔️:       INT_VECT comp;
// RDKit✔️✔️:       for (unsigned int idx = 0; idx < mol.getNumAtoms(); ++idx) {
// RDKit✔️✔️:         comp.push_back(idx);
// RDKit✔️✔️:       }
// RDKit✔️✔️:       (*fragsMolAtomMapping).push_back(comp);
// RDKit✔️✔️:     }
// RDKit✔️✔️:   } else {
// RDKit✔️✔️:     res.reserve(nFrags);
// RDKit✔️✔️:     for (int i = 0; i < nFrags; ++i) {
// RDKit✔️✔️:       boost::dynamic_bitset<> atomsInFrag(mol.getNumAtoms());
// RDKit✔️✔️:       INT_VECT comp;
// RDKit✔️✔️:       for (unsigned int idx = 0; idx < mol.getNumAtoms(); ++idx) {
// RDKit✔️✔️:         if ((*frags)[idx] == i) {
// RDKit✔️✔️:           comp.push_back(idx);
// RDKit✔️✔️:           atomsInFrag.set(idx);
// RDKit✔️✔️:         }
// RDKit✔️✔️:       }
// RDKit✔️✔️:       auto fragmentHasChallengingFeatures =
// RDKit✔️✔️:           [&](const INT_VECT &comp,
// RDKit✔️✔️:               const boost::dynamic_bitset<> &atomsInFrag) -> bool {
// RDKit✔️✔️:         for (auto idx : comp) {
// RDKit✔️✔️:           const auto atom = mol.getAtomWithIdx(idx);
// RDKit✔️✔️:           if (atom->getChiralTag() != Atom::ChiralType::CHI_UNSPECIFIED &&
// RDKit✔️✔️:               atom->getChiralTag() != Atom::ChiralType::CHI_OTHER) {
// RDKit✔️✔️:             return true;
// RDKit✔️✔️:           }
// RDKit✔️✔️:           for (auto bnd : mol.atomBonds(atom)) {
// RDKit✔️✔️:             if (atomsInFrag[bnd->getOtherAtomIdx(idx)]) {
// RDKit✔️✔️:               if (bnd->getStereo() != Bond::BondStereo::STEREONONE &&
// RDKit✔️✔️:                   bnd->getStereo() != Bond::BondStereo::STEREOANY) {
// RDKit✔️✔️:                 return true;
// RDKit✔️✔️:               }
// RDKit✔️✔️:             }
// RDKit✔️✔️:           }
// RDKit✔️✔️:         }
// RDKit✔️✔️:         for (auto sgroup : getSubstanceGroups(mol)) {
// RDKit✔️✔️:           for (auto aid : sgroup.getAtoms()) {
// RDKit✔️✔️:             if (atomsInFrag[aid]) { return true; }
// RDKit✔️✔️:           }
// RDKit✔️✔️:           for (auto aid : sgroup.getParentAtoms()) {
// RDKit✔️✔️:             if (atomsInFrag[aid]) { return true; }
// RDKit✔️✔️:           }
// RDKit✔️✔️:         }
// RDKit✔️✔️:         for (auto stereoGroup : mol.getStereoGroups()) {
// RDKit✔️✔️:           for (auto atom : stereoGroup.getAtoms()) {
// RDKit✔️✔️:             if (atomsInFrag[atom->getIdx()]) { return true; }
// RDKit✔️✔️:           }
// RDKit✔️✔️:           for (auto bond : stereoGroup.getBonds()) {
// RDKit✔️✔️:             if (atomsInFrag[bond->getBeginAtomIdx()] &&
// RDKit✔️✔️:                 atomsInFrag[bond->getEndAtomIdx()]) { return true; }
// RDKit✔️✔️:           }
// RDKit✔️✔️:         }
// RDKit✔️✔️:         return false;
// RDKit✔️✔️:       };
// RDKit✔️✔️:       if (comp.size() == 1 || (nFrags > 3 && !fragmentHasChallengingFeatures(comp, atomsInFrag))) {
// RDKit✔️✔️:         SubsetOptions opts{.sanitize = sanitizeFrags,
// RDKit✔️✔️:                            .clearComputedProps = true,
// RDKit✔️✔️:                            .copyCoordinates = copyConformers,
// RDKit✔️✔️:                            .method = SubsetMethod::BONDS_BETWEEN_ATOMS};
// RDKit✔️✔️:         std::vector<unsigned int> atoms{comp.begin(), comp.end()};
// RDKit✔️✔️:         auto submol = copyMolSubset(mol, atoms, info, opts);
// RDKit✔️✔️:         res.push_back(std::move(submol));
// RDKit✔️✔️:       } else {
// RDKit✔️✔️:         res.emplace_back(new RWMol(mol));
// RDKit✔️✔️:         frag->beginBatchEdit();
// RDKit✔️✔️:         for (unsigned int idx = 0; idx < mol.getNumAtoms(); ++idx) {
// RDKit✔️✔️:           if (!atomsInFrag[idx]) { frag->removeAtom(idx); }
// RDKit✔️✔️:         }
// RDKit✔️✔️:         frag->commitBatchEdit();
// RDKit✔️✔️:       }
// RDKit✔️✔️:       if (fragsMolAtomMapping) { (*fragsMolAtomMapping).push_back(comp); }
// RDKit✔️✔️:     }
// RDKit✔️✔️:   }
// RDKit✔️✔️:   if (!copyConformers) {
// RDKit✔️✔️:     for (auto &frag : res) { frag->clearConformers(); }
// RDKit✔️✔️:   }
// RDKit✔️✔️:   if (sanitizeFrags) {
// RDKit✔️✔️:     for (auto &frag : res) { sanitizeMol(*frag); }
// RDKit✔️✔️:   }
// RDKit✔️✔️:   std::vector<std::unique_ptr<ROMol>> finalRes;
// RDKit✔️✔️:   for (auto &r : res) {
// RDKit✔️✔️:     finalRes.emplace_back(r.get());
// RDKit✔️✔️:     r.release();
// RDKit✔️✔️:   }
// RDKit✔️✔️:   return finalRes;
// RDKit✔️✔️: }
// ---------------------------------------------------------------------------
pub fn get_mol_frags(mol: &Molecule) -> Result<Vec<Molecule>, FragmentError> {
    if mol.num_atoms() == 0 {
        return Err(FragmentError::EmptyMolecule);
    }

    let frag_groups = group_atoms_by_fragment(mol);

    if frag_groups.len() == 1 {
        // RDKit (line 716): res.emplace_back(new RWMol(mol));
        // Single fragment — return a copy of the input molecule
        return Ok(vec![mol.clone()]);
    }

    let mut result = Vec::with_capacity(frag_groups.len());
    for group in &frag_groups {
        let fragment = build_fragment_molecule(mol, group, true)?;
        result.push(fragment);
    }

    Ok(result)
}

// ---------------------------------------------------------------------------
// get_largest_fragment
//
// Returns the fragment with the most atoms.
// RDKit does not have a direct equivalent; this is a convenience wrapper
// over get_mol_frags.
// ---------------------------------------------------------------------------
pub fn get_largest_fragment(mol: &Molecule) -> Result<Molecule, FragmentError> {
    let fragments = get_mol_frags(mol)?;
    fragments
        .into_iter()
        .max_by_key(|frag| frag.num_atoms())
        .ok_or(FragmentError::EmptyMolecule)
}