votca 2026-dev
Loading...
Searching...
No Matches
fragmentsaturator.cc
Go to the documentation of this file.
1/*
2 * Copyright 2009-2026 The VOTCA Development Team
3 * (http://www.votca.org)
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License")
6 *
7 * You may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 */
19
20// VOTCA includes
21#include <algorithm>
22#include <cmath>
23#include <iostream>
26
27// OpenBabel includes
28#include <openbabel/atom.h>
29#include <openbabel/forcefield.h>
30#include <openbabel/mol.h>
31
32// Local VOTCA includes
34
35namespace votca {
36namespace xtp {
37
39 const QMMolecule& mol, double bond_length_angstrom) {
40 QMMolecule result(mol.getType(), mol.getId());
41
42 // Original atoms keep their indices; new H atoms are appended after
43 // them, so atom indices computed before saturation stay valid.
44 for (const QMAtom& atom : mol) {
45 result.push_back(atom);
46 }
47
48 // -1 for original atoms (see SaturationResult).
49 std::vector<Index> new_atom_parent_ids(mol.size(), -1);
50
51 double bond_length_bohr = bond_length_angstrom * tools::conv::ang2bohr;
52 Index new_index = mol.size();
53 for (const QMAtom& atom : mol) {
54 if (!atom.hasExternalBond()) {
55 continue;
56 }
57 // getExternalBondDirection() is a unit vector: it is normalized in
58 // setExternalBondDirection() and only rotated by SegmentMapper.
59 Eigen::Vector3d new_pos =
60 atom.getPos() + bond_length_bohr * atom.getExternalBondDirection();
61 QMAtom new_h(new_index, "H", new_pos);
62 // Record the new H-parent bond on both atoms. RelaxNewAtoms builds
63 // the OpenBabel connectivity from getBondedPartnerIds(); without
64 // this bond the H would be relaxed as an isolated atom. The parent
65 // is updated in result, where it has the same index as in mol.
66 new_h.AddBondedPartner(atom.getId());
67 result[atom.getId()].AddBondedPartner(new_index);
68 result.push_back(new_h);
69 new_atom_parent_ids.push_back(atom.getId());
70 new_index++;
71 }
72
73 return SaturationResult{result, new_atom_parent_ids};
74}
75
77 Index n_original_atoms,
78 Index n_steps) {
79 // Build the OBMol from the known connectivity
80 // (QMAtom::getBondedPartnerIds(), set by Md2QmEngine/SegmentMapper).
81 // OBMol::PerceiveBondOrders() requires the connectivity as input, and
82 // geometry-only bond perception is unreliable for newly added atoms.
83 OpenBabel::OBMol obmol;
84 obmol.BeginModify();
85 tools::Elements elements;
86 for (const QMAtom& atom : mol) {
87 OpenBabel::OBAtom* obatom = obmol.NewAtom();
88 obatom->SetAtomicNum(int(elements.getNucCrg(atom.getElement())));
89 // OpenBabel uses Angstrom, xtp uses Bohr.
90 Eigen::Vector3d pos_angstrom = atom.getPos() / tools::conv::ang2bohr;
91 obatom->SetVector(pos_angstrom.x(), pos_angstrom.y(), pos_angstrom.z());
92 }
93
94 // OBMol atom indices are 1-based. Bond order 1 is a placeholder;
95 // PerceiveBondOrders() derives the actual orders from connectivity and
96 // geometry.
97 for (const QMAtom& atom : mol) {
98 const Index* partners = atom.getBondedPartnerIds();
99 for (Index i = 0; i < QMAtom::kMaxBondedPartners; i++) {
100 Index partner_id = partners[i];
101 // Bonds are stored on both atoms; add each once, from the lower id.
102 if (partner_id == -1 || partner_id <= atom.getId()) {
103 continue;
104 }
105 obmol.AddBond(int(atom.getId()) + 1, int(partner_id) + 1, 1);
106 }
107 }
108 obmol.EndModify();
109 obmol.PerceiveBondOrders();
110
111 OpenBabel::OBForceField* pFF =
112 OpenBabel::OBForceField::FindForceField("MMFF94");
113 if (pFF == nullptr || !pFF->Setup(obmol)) {
114 // MMFF94 atom typing can fail, e.g. on aromatic-ring kekulization
115 // (openbabel/openbabel#2567); fall back to the more general UFF.
116 pFF = OpenBabel::OBForceField::FindForceField("UFF");
117 if (pFF == nullptr || !pFF->Setup(obmol)) {
118 throw std::runtime_error(
119 "FragmentSaturator::RelaxNewAtoms: could not set up either "
120 "MMFF94 or UFF for this fragment.");
121 }
122 }
123
124 // Fix all original atoms; only the appended H atoms
125 // (index >= n_original_atoms) move. Uses OBFFConstraints with
126 // Setup(mol, constraints), as documented in OpenBabel's forcefield.cpp.
127 OpenBabel::OBFFConstraints constraints;
128 for (Index i = 0; i < n_original_atoms; i++) {
129 constraints.AddAtomConstraint(int(i) + 1);
130 }
131 if (!pFF->Setup(obmol, constraints)) {
132 throw std::runtime_error(
133 "FragmentSaturator::RelaxNewAtoms: could not set up "
134 "constraints.");
135 }
136
137 // OpenBabel ignores the econv argument of ConjugateGradients() and
138 // ConjugateGradientsInitialize() (openbabel/openbabel#1366, #2804), so
139 // all n_steps would always run. The steps after convergence only
140 // accumulate platform-dependent rounding, which caused differences in
141 // the final couplings between platforms. The energy criterion of
142 // forcefield.cpp (IsNear(e_n2, e_n1, econv)) is therefore applied here,
143 // with OpenBabel's default econv = 1e-6.
144 double econv = 1e-6;
145 pFF->ConjugateGradientsInitialize(int(n_steps), econv);
146 double e_prev = pFF->Energy();
147 // Check every 10 steps to limit the cost of Energy() evaluations.
148 const Index check_interval = 10;
149 bool still_running = true;
150 for (Index step = 0; step < n_steps && still_running;
151 step += check_interval) {
152 Index steps_this_round = std::min(check_interval, n_steps - step);
153 still_running = pFF->ConjugateGradientsTakeNSteps(int(steps_this_round));
154 double e_now = pFF->Energy();
155 if (std::abs(e_now - e_prev) < econv) {
156 break;
157 }
158 e_prev = e_now;
159 }
160 pFF->GetCoordinates(obmol);
161
162 // Same elements and ids; only the free H atoms move (fixed atoms are
163 // unchanged up to rounding, not re-verified here).
164 QMMolecule result(mol.getType(), mol.getId());
165 Index idx = 0;
166 for (const QMAtom& atom : mol) {
167 OpenBabel::OBAtom* obatom = obmol.GetAtom(int(idx) + 1);
168 Eigen::Vector3d pos_bohr =
169 Eigen::Vector3d(obatom->GetX(), obatom->GetY(), obatom->GetZ()) *
171 QMAtom new_atom(atom.getId(), atom.getElement(), pos_bohr);
172 result.push_back(new_atom);
173 idx++;
174 }
175
176 return result;
177}
178
179} // namespace xtp
180} // namespace votca
information about an element
Definition elements.h:42
Index getNucCrg(std::string name)
Return the Nuclear charges of each atom. H - 1, He - 2, Na - 3 etc...
Definition elements.cc:36
const std::string & getType() const
void push_back(const T &atom)
static QMMolecule RelaxNewAtoms(const QMMolecule &mol, Index n_original_atoms, Index n_steps=500)
static SaturationResult SaturateExternalBonds(const QMMolecule &mol, double bond_length_angstrom=kDefaultCHBondLengthAngstrom)
container for QM atoms
Definition qmatom.h:37
void AddBondedPartner(Index partner_id)
Definition qmatom.h:120
static constexpr Index kMaxBondedPartners
Definition qmatom.h:42
const double ang2bohr
Definition constants.h:48
Charge transport classes.
Definition ERIs.h:28
Provides a means for comparing floating point numbers.
Definition basebead.h:33
Eigen::Index Index
Definition types.h:26