votca 2026-dev
Loading...
Searching...
No Matches
md2qmengine.cc
Go to the documentation of this file.
1/*
2 * Copyright 2009-2021 The VOTCA Development Team (http://www.votca.org)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18// Local VOTCA includes
20
21namespace votca {
22namespace xtp {
23
25 std::string molkey = "topology.molecules.molecule";
26 std::vector<tools::Property*> molecules = topology_map.Select(molkey);
27 if (SameValueForMultipleEntries<std::string>(molecules, "mdname")) {
28 throw std::runtime_error("Multiple molecules have same mdname");
29 }
30 std::string segkey = "segments.segment";
31 std::vector<tools::Property*> segments_all;
32 for (tools::Property* mol : molecules) {
33 std::vector<tools::Property*> segments = mol->Select(segkey);
34 if (SameValueForMultipleEntries<std::string>(segments, "name")) {
35 throw std::runtime_error("Multiple segments in molecule:" +
36 mol->get("mdname").as<std::string>() +
37 " have same name");
38 }
39 segments_all.insert(segments_all.end(), segments.begin(), segments.end());
40 for (tools::Property* seg : segments) {
41 std::string fragkey = "fragments.fragment";
42 std::vector<tools::Property*> fragments = seg->Select(fragkey);
43 if (SameValueForMultipleEntries<std::string>(fragments, "name")) {
44 throw std::runtime_error(
45 "Multiple fragments have same name in molecule " +
46 mol->get("mdname").as<std::string>() + " segment " +
47 seg->get("name").as<std::string>());
48 }
49
50 std::vector<std::string> atomnames_seg;
51 for (tools::Property* frag : fragments) {
52 std::vector<std::string> atomnames =
53 frag->get("mdatoms").as<std::vector<std::string>>();
54 atomnames_seg.insert(atomnames_seg.end(), atomnames.begin(),
55 atomnames.end());
56 }
57 std::sort(atomnames_seg.begin(), atomnames_seg.end()); // O(N log N)
58 if (adjacent_find(atomnames_seg.begin(), atomnames_seg.end()) !=
59 atomnames_seg.end()) {
60 throw std::runtime_error(
61 "Multiple mdatoms have same identifier in molecule " +
62 mol->get("mdname").as<std::string>() + " segment " +
63 seg->get("name").as<std::string>());
64 }
65 }
66 }
67 if (SameValueForMultipleEntries<std::string>(segments_all, "name")) {
68 throw std::runtime_error("Multiple segments have same name");
69 }
70}
71
73 const csg::Molecule* mol, const std::vector<Index>& atom_ids_map) const {
74 std::vector<Index> IDs;
75 IDs.reserve(mol->BeadCount());
76 for (const csg::Bead* bead : mol->Beads()) {
77 IDs.push_back(bead->getId());
78 }
79 std::sort(IDs.begin(), IDs.end());
80
81 if (atom_ids_map.empty()) {
82 throw std::runtime_error("Molecule " + mol->getName() +
83 " is not defined in the mapping file.");
84 }
85 if (atom_ids_map.size() != IDs.size()) {
86 throw std::runtime_error(
87 "Molecule " + mol->getName() + " has " + std::to_string(IDs.size()) +
88 " atoms in the MD topology but " + std::to_string(atom_ids_map.size()) +
89 " in the mapping file.");
90 }
91 Index offset = IDs[0] - atom_ids_map[0];
92 for (Index i = 1; i < Index(IDs.size()); i++) {
93 if (IDs[i] - atom_ids_map[i] != offset) {
94 throw std::runtime_error(
95 "AtomIds offset could not be determined, either our MD trajectory or "
96 "your mapping file have wrong Atom ids");
97 }
98 }
99 return offset;
100}
101
102bool Md2QmEngine::CheckMolWhole(const Topology& top, const Segment& seg) const {
103 Eigen::Vector3d CoM = seg.getPos();
104 bool whole = true;
105 for (const Atom& a : seg) {
106 Eigen::Vector3d r = a.getPos() - CoM;
107 Eigen::Vector3d r_pbc = top.PbShortestConnect(CoM, a.getPos());
108 Eigen::Vector3d shift = r_pbc - r;
109 if (shift.norm() > 1e-9) {
110 whole = false;
111 break;
112 }
113 }
114 return whole;
115}
116
118 for (Segment& seg : top.Segments()) {
119 seg.calcPos();
120 while (!CheckMolWhole(top, seg)) {
121 Eigen::Vector3d CoM = seg.getPos();
122 for (Atom& a : seg) {
123 Eigen::Vector3d r = a.getPos() - CoM;
124 Eigen::Vector3d r_pbc = top.PbShortestConnect(CoM, a.getPos());
125 Eigen::Vector3d shift = r_pbc - r;
126 if (shift.norm() > 1e-9) {
127 a.Translate(shift);
128 }
129 }
130 seg.calcPos();
131 }
132 }
133}
134
136
137 tools::Property topology_map;
138 topology_map.LoadFromXML(mapfile_);
139 CheckMappingFile(topology_map);
140 Topology xtptop;
141 xtptop.setStep(top.getStep());
142 xtptop.setTime(top.getTime());
143 xtptop.setBox(top.getBox() * tools::conv::nm2bohr, top.getBoxType());
144
145 // which segmentname does an atom belong to molname atomid
146 std::map<std::string, std::map<Index, std::string>> MolToSegMap;
147
148 // which atomids belong to molname
149 std::map<std::string, std::vector<Index>> MolToAtomIds;
150
151 // names of segments in one molecule;
152 std::map<std::string, std::vector<std::string>> SegsinMol;
153
154 std::string molkey = "topology.molecules.molecule";
155 std::vector<tools::Property*> molecules = topology_map.Select(molkey);
156 std::string segkey = "segments.segment";
157
158 for (tools::Property* mol : molecules) {
159 // get the name of this molecule
160 std::string molname = mol->get("mdname").as<std::string>();
161 // get all segment-mapping info
162 std::vector<tools::Property*> segments = mol->Select(segkey);
163 std::vector<std::string> segnames;
164 std::vector<Index> atomids;
165 // now go through all the defined segments
166 for (tools::Property* seg : segments) {
167 // get the name of this segment and add to segnames vector
168 std::string segname = seg->get("name").as<std::string>();
169 segnames.push_back(segname);
170 if (votca::Log::verbose()) {
171 std::cout << "... ... processing mapping information for segment "
172 << segname << std::endl;
173 }
174 std::string fragkey = "fragments.fragment";
175 // get all fragement mapping info
176 std::vector<tools::Property*> fragments = seg->Select(fragkey);
177 // go over all fragments in this segement
178 for (tools::Property* frag : fragments) {
179 // get all mdatom names from this fragment
180 std::vector<std::string> atomnames =
181 frag->get("mdatoms").as<std::vector<std::string>>();
182 // go over all atoms
183 for (const std::string& atomname : atomnames) {
184 // split atom entry at :
185 tools::Tokenizer tok_atom_name(atomname, ":");
186 std::vector<std::string> entries = tok_atom_name.ToVector();
187 if (entries.size() != 3) {
188 throw std::runtime_error("Atom entry " + atomname +
189 " is not well formatted");
190 }
191 // format should be RESNUM:ATOMNAME:ATOMID we do not care about the
192 // first two
193 Index atomid = 0;
194 try {
195 atomid = std::stoi(entries[2]);
196 } catch (std::invalid_argument& e) {
197 throw std::runtime_error("Atom entry " + atomname +
198 " is not well formatted");
199 }
200 if (votca::Log::verbose()) {
201 std::cout << "... ... processing mapping information for atom "
202 << atomname << " with ID " << atomid << std::endl;
203 }
204 atomids.push_back(atomid);
205 MolToSegMap[molname][atomid] = segname;
206 }
207 }
208 }
209 std::sort(atomids.begin(), atomids.end());
210 MolToAtomIds[molname] = atomids;
211 if (votca::Log::verbose()) {
212 std::cout << "... molecule " << molname << " has " << segnames.size()
213 << " segment(s)" << std::endl;
214 }
215 SegsinMol[molname] = segnames;
216 }
217
218 // Lookup bead ID -> IDs of directly bonded beads, built from the bonded
219 // interactions of the MD topology (purely geometric, independent of the
220 // segment/fragment mapping). Only 2-bead interactions (bonds) are used;
221 // angles and dihedrals are skipped.
222 std::map<Index, std::vector<Index>> bead_bonded_partners;
223 for (csg::Interaction* interaction : top.BondedInteractions()) {
224 if (interaction->BeadCount() != 2) {
225 continue;
226 }
227 Index id1 = interaction->getBeadId(0);
228 Index id2 = interaction->getBeadId(1);
229 bead_bonded_partners[id1].push_back(id2);
230 bead_bonded_partners[id2].push_back(id1);
231 }
232
233 // Always printed (not only in verbose mode): without bonds no external
234 // bonds can be detected below, so the H-saturation of cut segment
235 // boundaries in IPodCoupling::EvalJob (see transport_theory.rst,
236 // "H-Saturation of Cut Segment Boundaries") silently leaves dangling
237 // valences. This happened e.g. with GMXTopologyReader before it read bonds.
238 if (bead_bonded_partners.empty()) {
239 std::cout
240 << "\nWARNING: the MD topology contains no bonds (no 2-bead bonded "
241 "interactions found); the topology reader may only provide atom "
242 "positions. External bonds at cut segment boundaries cannot be "
243 "detected, so automatic H-saturation (e.g. in ipodcoupling) will "
244 "do nothing. Use a topology file/reader that provides bonds, or "
245 "xtp_map --guess-bonds."
246 << std::endl;
247 }
248
249 std::vector<Index> atoms_with_several_external_bonds;
250
251 // go through all molecules in MD topology
252 for (const csg::Molecule& mol : top.Molecules()) {
253
254 // lookup all segment *names* in this molecule
255 const std::vector<std::string> segnames = SegsinMol[mol.getName()];
256
257 std::vector<Segment>& topology_segments = xtptop.Segments();
258 Index IdOffset = DetermineAtomNumOffset(&mol, MolToAtomIds[mol.getName()]);
259
260 if (votca::Log::verbose()) {
261 std::cout << "... Mapping molecule " << mol.getId() << ", name "
262 << mol.getName() << ", # of segments " << segnames.size()
263 << ", atomID offset " << IdOffset << std::endl;
264 }
265
266 for (const std::string& segname : segnames) {
267
268 Index segid = topology_segments.size();
269 // construct a segment
270 Segment this_segment = Segment(segname, segid);
271 this_segment.AddMoleculeId(mol.getId());
272
273 // create atomlist
274 for (const csg::Bead* bead : mol.Beads()) {
275 // check if it belongs to this segment, and add it
276 if (segname == MolToSegMap[mol.getName()][bead->getId() - IdOffset]) {
277 Atom atom(bead->getResnr(), bead->getName(), bead->getId(),
278 bead->getPos() * tools::conv::nm2bohr, bead->getType());
279
280 // A bonded partner in a different segment (or in no segment,
281 // e.g. an unmapped atom) marks a bond crossing the segment
282 // boundary. Its direction is stored on the atom (in MD
283 // orientation; SegmentMapper rotates it with the QM template)
284 // for later H-saturation. Only the first such partner is stored;
285 // atoms with more are counted and reported below.
286 auto it = bead_bonded_partners.find(bead->getId());
287 if (it != bead_bonded_partners.end()) {
288 Index n_external = 0;
289 for (Index partner_id : it->second) {
290 const csg::Bead* partner_bead = top.getBead(partner_id);
291 // MoleculeByIndex() is not const, so the partner's molecule
292 // is looked up by matching getMoleculeId() against
293 // Molecule::getId(), the same ID used for AddMoleculeId above.
294 const csg::Molecule* partner_mol = nullptr;
295 for (const csg::Molecule& candidate : top.Molecules()) {
296 if (candidate.getId() == partner_bead->getMoleculeId()) {
297 partner_mol = &candidate;
298 break;
299 }
300 }
301 if (partner_mol == nullptr) {
302 continue;
303 }
304 Index partner_offset = DetermineAtomNumOffset(
305 partner_mol, MolToAtomIds[partner_mol->getName()]);
306 std::string partner_segname =
307 MolToSegMap[partner_mol->getName()]
308 [partner_bead->getId() - partner_offset];
309 if (partner_segname != segname) {
310 if (n_external == 0) {
311 // Minimum image: the bond may cross the box boundary.
312 Eigen::Vector3d direction =
313 top.BCShortestConnection(bead->getPos(),
314 partner_bead->getPos()) *
316 atom.setExternalBondDirection(direction,
317 partner_bead->getId());
318 }
319 n_external++;
320 }
321 }
322 if (n_external > 1) {
323 atoms_with_several_external_bonds.push_back(bead->getId());
324 }
325 }
326
327 // Store all bonded partners (not only external ones); the
328 // fragment relaxation in FragmentSaturator needs the full internal
329 // connectivity (see Atom::getBondedPartnerIds). These are MD-level
330 // IDs, translated to QM-level IDs in SegmentMapper.
331 if (it != bead_bonded_partners.end()) {
332 for (Index partner_id : it->second) {
333 atom.AddBondedPartner(partner_id);
334 }
335 }
336
337 this_segment.push_back(atom);
338 }
339 }
340 // add segment to topology
341 topology_segments.push_back(this_segment);
342 }
343 }
344
345 if (!atoms_with_several_external_bonds.empty()) {
346 std::cout << "\nWARNING: " << atoms_with_several_external_bonds.size()
347 << " atom(s) have bonds into more than one other segment (first: "
348 "MD atom "
349 << atoms_with_several_external_bonds.front()
350 << "). Only one external bond per atom is stored, so "
351 "H-saturation of cut segment boundaries (e.g. ipodcoupling) "
352 "and the search for linking segments use only that one. "
353 "Choose segment boundaries that cut at most one bond per "
354 "atom.\n"
355 << std::endl;
356 }
357
358 // Second pass: resolve the MD atom ID of each external-bond partner
359 // (getExternalBondPartnerAtomId(), transient) to the ID of the segment it
360 // belongs to (getExternalBondPartnerSegmentId(), persisted). This cannot
361 // be done in the loop above, since later segments do not exist yet there.
362 // The segment ID identifies which segment a bond crosses into, e.g. to
363 // decide whether the bond is satisfied within an assembled supermolecule.
364 std::map<Index, Index> md_atom_id_to_segment_id;
365 for (const Segment& seg : xtptop.Segments()) {
366 for (const Atom& segatom : seg) {
367 md_atom_id_to_segment_id[segatom.getId()] = seg.getId();
368 }
369 }
370 for (Segment& seg : xtptop.Segments()) {
371 for (Atom& segatom : seg) {
372 if (!segatom.hasExternalBond()) {
373 continue;
374 }
375 auto it =
376 md_atom_id_to_segment_id.find(segatom.getExternalBondPartnerAtomId());
377 if (it != md_atom_id_to_segment_id.end()) {
378 segatom.setExternalBondPartnerSegmentId(it->second);
379 }
380 }
381 }
382
383 MakeSegmentsWholePBC(xtptop);
384
385 return xtptop;
386}
387
388template <class T>
390 const std::vector<tools::Property*>& props, std::string valuetag) const {
391 std::vector<T> entries;
392 for (tools::Property* prop : props) {
393 entries.push_back(prop->get(valuetag).as<T>());
394 }
395 std::sort(entries.begin(), entries.end()); // O(N log N)
396 return adjacent_find(entries.begin(), entries.end()) != entries.end();
397}
398
399} // namespace xtp
400} // namespace votca
virtual const Eigen::Vector3d & getPos() const
Definition basebead.h:166
Index getMoleculeId() const noexcept
Get the id of the molecule the bead is a part of, if the molecule id has not been set return topology...
Definition basebead.h:78
Index getId() const noexcept
Gets the id of the bead.
Definition basebead.h:52
information about a bead
Definition bead.h:50
base class for all interactions
Definition interaction.h:40
information about molecules
Definition molecule.h:45
const std::string & getName() const
get the name of the molecule
Definition molecule.h:51
Index BeadCount() const
get the number of beads in the molecule
Definition molecule.h:65
const std::vector< Bead * > & Beads() const
Definition molecule.h:67
topology of the whole system
Definition topology.h:81
double getTime() const
Definition topology.h:317
BoundaryCondition::eBoxtype getBoxType() const
Definition topology.h:394
const Eigen::Matrix3d & getBox() const
Definition topology.h:298
Index getStep() const
Definition topology.h:329
Eigen::Vector3d BCShortestConnection(const Eigen::Vector3d &r_i, const Eigen::Vector3d &r_j) const
calculate shortest vector connecting two points
Definition topology.cc:238
Bead * getBead(const Index i)
Returns a pointer to the bead with index i.
Definition topology.h:227
MoleculeContainer & Molecules()
Definition topology.h:182
InteractionContainer & BondedInteractions()
Definition topology.h:189
class to manage program options with xml serialization functionality
Definition property.h:55
std::vector< Property * > Select(const std::string &filter)
select property based on a filter
Definition property.cc:185
void LoadFromXML(std::string filename)
Definition property.cc:238
break string into words
Definition tokenizer.h:72
std::vector< T > ToVector()
store all words in a vector of type T, does type conversion.
Definition tokenizer.h:109
void push_back(const T &atom)
const Eigen::Vector3d & getPos() const
void AddBondedPartner(Index partner_id)
Definition atom.h:121
void setExternalBondDirection(const Eigen::Vector3d &dir, Index partner_atom_id)
Definition atom.h:97
void CheckMappingFile(tools::Property &topology_map) const
void MakeSegmentsWholePBC(Topology &top) const
Index DetermineAtomNumOffset(const csg::Molecule *mol, const std::vector< Index > &atom_ids_map) const
bool SameValueForMultipleEntries(const std::vector< tools::Property * > &props, std::string tag) const
Topology map(const csg::Topology &top) const
bool CheckMolWhole(const Topology &top, const Segment &seg) const
void AddMoleculeId(Index id)
Definition segment.h:91
Container for segments and box and atoms.
Definition topology.h:41
Eigen::Vector3d PbShortestConnect(const Eigen::Vector3d &r1, const Eigen::Vector3d &r2) const
Definition topology.cc:140
void setTime(double time)
Definition topology.h:78
void setBox(const Eigen::Matrix3d &box, csg::BoundaryCondition::eBoxtype boxtype=csg::BoundaryCondition::typeAuto)
Definition topology.cc:85
std::vector< Segment > & Segments()
Definition topology.h:58
void setStep(Index step)
Definition topology.h:76
const double nm2bohr
Definition constants.h:47
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
static bool verbose()
Definition globals.h:32