votca 2026-dev
Loading...
Searching...
No Matches
xtp_map.cc
Go to the documentation of this file.
1/*
2 * Copyright 2009-2021 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// Standard includes
21#include <fstream>
22#include <iostream>
23#include <stdexcept>
24
25// VOTCA includes
32#include <votca/tools/globals.h>
33
34// Local VOTCA includes
37#include "votca/xtp/topology.h"
38#include "votca/xtp/version.h"
39
40using namespace std;
41
42namespace CSG = votca::csg;
43namespace XTP = votca::xtp;
44namespace TOOLS = votca::tools;
45
46class XtpMap : public TOOLS::Application {
47
48 public:
49 string ProgramName() override { return "xtp_map"; }
50 void HelpText(ostream& out) override {
51 out << "Generates QM|MD topology" << endl;
52 }
53 void ShowHelpText(std::ostream& out) override;
54
55 void Initialize() override;
56 bool EvaluateOptions() override;
57 void Run() override;
58
59 protected:
60};
61
62// Bondi (1964) van der Waals radii in Angstrom. VMD's bond-detection
63// heuristic, used in GuessBonds, creates a bond when the separation of two
64// atoms is below 60% of the sum of their vdW radii. The ChelpG/MK radii in
65// votca::tools::Elements are fitting radii for electrostatic potentials and
66// are deliberately not used here.
67static const std::map<std::string, double> kBondiVdWRadiusAngstrom = {
68 {"H", 1.20}, {"C", 1.70}, {"N", 1.55}, {"O", 1.52},
69 {"F", 1.47}, {"P", 1.80}, {"S", 1.80}, {"Cl", 1.75},
70};
71
72// Opt-in (--guess-bonds) fallback that guesses bond connectivity from atom
73// positions for topologies without any bonds. Bond connectivity is required
74// for the H-saturation of cut segment boundaries (IPodCoupling::EvalJob, see
75// the warning in Md2QmEngine::map). This is never done automatically: a wrong
76// bond silently corrupts external-bond detection and RelaxNewAtoms, whereas a
77// missing bond only disables saturation, which is already warned about.
78//
79// Only atom pairs within the same MD molecule are tested. This avoids false
80// bonds to neighbouring molecules in dense periodic systems and reduces the
81// cost from O(N^2) to O(N k), with k the molecule size. Close contacts within
82// one molecule (e.g. a folded chain) can still produce false bonds, so every
83// guessed bond is written to guessed_bonds_report.txt for inspection.
85 if (!top.BondedInteractions().empty()) {
86 throw runtime_error(
87 "--guess-bonds was requested, but the topology already contains "
88 "bonds. Guessing additional bonds could duplicate or conflict with "
89 "them; --guess-bonds is only allowed for topologies without bonds.");
90 }
91
92 std::ofstream report("guessed_bonds_report.txt");
93 report << "# Bonds guessed from atom positions alone, via --guess-bonds\n"
94 << "# (van der Waals radii heuristic, restricted to atom pairs "
95 "within the same molecule). Review before using the guessed "
96 "connectivity.\n"
97 << "# mol_id atom1_id atom1_name atom2_id atom2_name "
98 "distance[Ang] cutoff[Ang]\n";
99
100 votca::Index guessed_count = 0;
101 for (const CSG::Molecule& mol : top.Molecules()) {
102 votca::Index nbeads = mol.BeadCount();
103 for (votca::Index i = 0; i < nbeads; i++) {
104 const CSG::Bead* bead1 = mol.getBead(i);
105 auto it1 = kBondiVdWRadiusAngstrom.find(bead1->getElement());
106 if (it1 == kBondiVdWRadiusAngstrom.end()) {
107 continue;
108 }
109 for (votca::Index j = i + 1; j < nbeads; j++) {
110 const CSG::Bead* bead2 = mol.getBead(j);
111 auto it2 = kBondiVdWRadiusAngstrom.find(bead2->getElement());
112 if (it2 == kBondiVdWRadiusAngstrom.end()) {
113 continue;
114 }
115 // Minimum-image distance; BCShortestConnection(r_i, r_j) returns
116 // r_j - r_i, only its norm is used here.
117 double distance_nm =
118 top.BCShortestConnection(bead1->getPos(), bead2->getPos()).norm();
119 double distance_ang = distance_nm * votca::tools::conv::nm2ang;
120 double cutoff_ang = 0.6 * (it1->second + it2->second);
121 if (distance_ang < cutoff_ang) {
122 // A new IBond has an empty group, and
123 // Topology::AddBondedInteraction asserts a non-empty getGroup(),
124 // so the group must be set first (as in gmxtopologyreader.cc).
125 CSG::Interaction* ic = new CSG::IBond(bead1->getId(), bead2->getId());
126 ic->setGroup("BONDS");
127 top.AddBondedInteraction(ic);
128 report << " " << mol.getId() << " " << bead1->getId() << " "
129 << bead1->getName() << " " << bead2->getId() << " "
130 << bead2->getName() << " "
131 << (boost::format("%1$.3f") % distance_ang).str() << " "
132 << (boost::format("%1$.3f") % cutoff_ang).str() << "\n";
133 guessed_count++;
134 }
135 }
136 }
137 }
138 report.close();
139
140 cout << "\n--guess-bonds: guessed " << guessed_count
141 << " bonds from atom positions (van der Waals radii heuristic, "
142 "restricted to atom pairs within the same molecule). Review "
143 "guessed_bonds_report.txt before using them."
144 << endl;
145}
146
147namespace propt = boost::program_options;
148
150
154
155 AddProgramOptions()("topology,t", propt::value<string>(), " topology");
156 AddProgramOptions()("coordinates,c", propt::value<string>(),
157 " coordinates or trajectory");
158 AddProgramOptions()("segments,s", propt::value<string>(),
159 " definition of segments and fragments");
160 AddProgramOptions()("makesegments,m", " write out a skeleton segments file");
161 AddProgramOptions()("file,f", propt::value<string>(), " state file");
162 AddProgramOptions()("first-frame,i",
163 propt::value<votca::Index>()->default_value(0),
164 " start from this frame");
165 AddProgramOptions()("begin,b", propt::value<double>()->default_value(0.0),
166 " start time in simulation");
167 AddProgramOptions()("nframes,n",
168 propt::value<votca::Index>()->default_value(1),
169 " number of frames to process");
171 "guess-bonds",
172 " guess bond connectivity from atom positions for topologies "
173 "without bonds, using VMD's van der Waals radii heuristic restricted "
174 "to atom pairs within the same MD molecule. Fails if the topology "
175 "already contains bonds. All guessed bonds are written to "
176 "guessed_bonds_report.txt; review them, the heuristic can produce "
177 "false bonds.");
178}
179
181
182 CheckRequired("topology", "Missing topology file");
183 CheckRequired("segments", "Missing segment definition file");
184 CheckRequired("coordinates", "Missing trajectory input");
185 if (!(OptionsMap().count("makesegments"))) {
186 CheckRequired("file", "Missing state file");
187 }
188 return 1;
189}
190
192
193 std::string name = ProgramName();
194 if (VersionString() != "") {
195 name = name + ", version " + VersionString();
196 }
198
199 // ++++++++++++++++++++++++++++ //
200 // Create MD topology from file //
201 // ++++++++++++++++++++++++++++ //
202
203 // Create topology reader
204 string topfile = OptionsMap()["topology"].as<string>();
205 std::unique_ptr<CSG::TopologyReader> topread =
206 CSG::TopReaderFactory().Create(topfile);
207
208 if (topread == nullptr) {
209 throw runtime_error(string("Input format not supported: ") +
210 OptionsMap()["topology"].as<string>());
211 }
212 CSG::Topology mdtopol;
213 topread->ReadTopology(topfile, mdtopol);
214 if (votca::Log::verbose()) {
215 cout << "Read MD topology from " << topfile << ": Found "
216 << mdtopol.BeadCount() << " atoms in " << mdtopol.MoleculeCount()
217 << " molecules. " << endl;
218 }
219
220 // ++++++++++++++++++++++++++++++ //
221 // Create MD trajectory from file //
222 // ++++++++++++++++++++++++++++++ //
223
224 // Create trajectory reader and initialize
225 string trjfile = OptionsMap()["coordinates"].as<string>();
226 std::unique_ptr<CSG::TrajectoryReader> trjread =
227 CSG::TrjReaderFactory().Create(trjfile);
228
229 if (trjread == nullptr) {
230 throw runtime_error(string("Input format not supported: ") +
231 OptionsMap()["coordinates"].as<string>());
232 }
233 trjread->Open(trjfile);
234 trjread->FirstFrame(mdtopol);
235
236 if (OptionsMap().count("guess-bonds")) {
237 GuessBonds(mdtopol);
238 }
239
240 string mapfile = OptionsMap()["segments"].as<string>();
241 if (OptionsMap().count("makesegments")) {
242 if (TOOLS::filesystem::FileExists(mapfile)) {
243 cout << endl
244 << "xtp_map : map file '" << mapfile
245 << "' already in use. Delete the current mapfile or specify a "
246 "different name."
247 << endl;
248 return;
249 }
250
251 cout << " Writing template mapfile to " << mapfile << std::endl;
252
253 TOOLS::Property mapfile_prop("topology", "", "");
254 TOOLS::Property& molecules = mapfile_prop.add("molecules", "");
255
256 std::map<std::string, const CSG::Molecule*> firstmolecule;
257
258 std::map<std::string, votca::Index> molecule_names;
259 for (const CSG::Molecule& mol : mdtopol.Molecules()) {
260 if (!molecule_names.count(mol.getName())) {
261 firstmolecule[mol.getName()] = &mol;
262 }
263 molecule_names[mol.getName()]++;
264 }
265 for (const auto& mol : molecule_names) {
266 std::cout << "Found " << mol.second << " with name " << mol.first
267 << std::endl;
268 }
269 for (const auto& mol : molecule_names) {
270 TOOLS::Property& molecule = molecules.add("molecule", "");
271 molecule.add("mdname", mol.first);
272 TOOLS::Property& segments = molecule.add("segments", "");
273 TOOLS::Property& segment = segments.add("segment", "");
274 segment.add("name", "UPTOYOU_BUTUNIQUE");
275 segment.add("qmcoords_n", "XYZFILE_GROUNDSTATE");
276 segment.add("multipoles_n", "MPSFILE_GROUNDSTATE");
277 segment.add("map2md", "WANTTOMAPTOMDGEOMETRY");
278 segment.add("U_xX_nN_h", "REORG1_hole");
279 segment.add("U_nX_nN_h", "REORG2_hole");
280 segment.add("U_xN_xX_h", "REORG3_hole");
281 TOOLS::Property& fragments = segment.add("fragments", "");
282 TOOLS::Property& fragment = fragments.add("fragment", "");
283 std::string atomnames = "";
284 const CSG::Molecule* csgmol = firstmolecule[mol.first];
285 std::vector<const CSG::Bead*> sortedbeads;
286 sortedbeads.reserve(csgmol->BeadCount());
287 for (const CSG::Bead* bead : csgmol->Beads()) {
288 sortedbeads.push_back(bead);
289 }
290 std::sort(sortedbeads.begin(), sortedbeads.end(),
291 [&](const CSG::Bead* b1, const CSG::Bead* b2) {
292 return b1->getId() < b2->getId();
293 });
294
295 for (const CSG::Bead* bead : sortedbeads) {
296 atomnames += " " + std::to_string(bead->getResnr()) + ":" +
297 bead->getName() + ":" + std::to_string(bead->getId());
298 }
299 fragment.add("name", "UPTOYOU_BUTUNIQUE");
300 fragment.add("mdatoms", atomnames);
301 fragment.add("qmatoms", "IDS of QMATOMS i.e 0:C 1:H 2:C");
302 fragment.add("mpoles", "IDS of MPOLES i.e 0:C 1:H 2:C");
303 fragment.add("weights",
304 "weights for mapping(often atomic mass) i.e. 12 1 12");
305 fragment.add("localframe", "IDs of up to 3 qmatoms or mpoles i.e. 0 1 2");
306 std::ofstream template_mapfile(mapfile);
307 template_mapfile << mapfile_prop << std::flush;
308 template_mapfile.close();
309
310 std::cout << "MOLECULETYPE " << csgmol->getName() << std::endl;
311 std::cout << "SAMPLECOORDINATES" << std::endl;
312 std::cout << "ID NAME COORDINATES[Angstroem] " << std::endl;
313 for (const CSG::Bead* bead : sortedbeads) {
314 Eigen::Vector3d pos = bead->getPos() * votca::tools::conv::nm2ang;
315 std::string output =
316 (boost::format("%1$i %2$s %3$+1.4f %4$+1.4f %5$+1.4f\n") %
317 bead->getId() % bead->getName() % pos[0] % pos[1] % pos[2])
318 .str();
319 std::cout << output;
320 }
321 }
322 std::cout << std::flush;
323 return;
324 }
325
326 if (!TOOLS::filesystem::FileExists(mapfile)) {
327 cout << endl
328 << "xtp_map : map file '" << mapfile << "' could not be found."
329 << endl;
330 return;
331 }
332 XTP::Md2QmEngine md2qm(mapfile);
333
334 votca::Index firstFrame = OptionsMap()["first-frame"].as<votca::Index>();
335 votca::Index nFrames = OptionsMap()["nframes"].as<votca::Index>();
336 bool beginAt = false;
337 double time = OptionsMap()["begin"].as<double>();
338 double startTime = mdtopol.getTime();
339 if (time > 0.0) {
340 beginAt = true;
341 startTime = time;
342 }
343
344 // Extract first frame specified
345 bool hasFrame;
346 votca::Index frames_found = 0;
347 votca::Index firstframecounter = firstFrame;
348 for (hasFrame = true; hasFrame == true;
349 hasFrame = trjread->NextFrame(mdtopol)) {
350 frames_found++;
351 if (((mdtopol.getTime() < startTime) && beginAt) || firstframecounter > 0) {
352 firstframecounter--;
353 continue;
354 }
355 break;
356 }
357 if (!hasFrame) {
358 trjread->Close();
359
360 throw runtime_error("Time or frame number exceeds trajectory length");
361 }
362 if (votca::Log::verbose()) {
363 cout << "Read MD trajectory from " << trjfile << ": found " << frames_found
364 << " frames, starting from frame " << firstFrame << endl;
365 }
366 // +++++++++++++++++++++++++ //
367 // Convert MD to QM Topology //
368 // +++++++++++++++++++++++++ //
369
370 string statefile = OptionsMap()["file"].as<string>();
371 if (TOOLS::filesystem::FileExists(statefile)) {
372 cout << endl
373 << "xtp_map : state file '" << statefile
374 << "' already in use. Delete the current statefile or specify a "
375 "different name."
376 << endl;
377 return;
378 }
379
380 XTP::StateSaver statsav(statefile);
381 votca::Index laststep =
382 -1; // for some formats no step is given out so we check if the step
383 for (votca::Index saved = 0; hasFrame && saved < nFrames;
384 hasFrame = trjread->NextFrame(mdtopol), saved++) {
385 if (mdtopol.getStep() == laststep) {
386 mdtopol.setStep(laststep + 1);
387 }
388 laststep = mdtopol.getStep();
389 XTP::Topology qmtopol = md2qm.map(mdtopol);
390 statsav.WriteFrame(qmtopol);
391 }
392}
393
394void XtpMap::ShowHelpText(std::ostream& out) {
395 string name = ProgramName();
396 if (VersionString() != "") {
397 name = name + ", version " + VersionString();
398 }
400 HelpText(out);
401 out << "\n\n" << VisibleOptions() << endl;
402}
403
404int main(int argc, char** argv) {
405 XtpMap xtpmap;
406 return xtpmap.Exec(argc, argv);
407}
void Run() override
Main body of application.
Definition xtp_map.cc:191
string ProgramName() override
program name
Definition xtp_map.cc:49
void ShowHelpText(std::ostream &out) override
Definition xtp_map.cc:394
void HelpText(ostream &out) override
help text of application without version information
Definition xtp_map.cc:50
void Initialize() override
Initialize application data.
Definition xtp_map.cc:149
bool EvaluateOptions() override
Process command line options.
Definition xtp_map.cc:180
std::string getElement() const noexcept
Returns the element type of the bead.
Definition basebead.h:98
virtual const Eigen::Vector3d & getPos() const
Definition basebead.h:166
std::string getName() const
Gets the name of the bead.
Definition basebead.h:58
Index getId() const noexcept
Gets the id of the bead.
Definition basebead.h:52
information about a bead
Definition bead.h:50
bond interaction
base class for all interactions
Definition interaction.h:40
void setGroup(const std::string &group)
Definition interaction.h:49
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
static void RegisterPlugins(void)
topology of the whole system
Definition topology.h:81
double getTime() const
Definition topology.h:317
Index MoleculeCount() const
number of molecules in the system
Definition topology.h:144
void AddBondedInteraction(Interaction *ic)
Definition topology.cc:188
Index BeadCount() const
Definition topology.h:150
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
void setStep(Index s)
Definition topology.h:323
MoleculeContainer & Molecules()
Definition topology.h:182
InteractionContainer & BondedInteractions()
Definition topology.h:189
int Exec(int argc, char **argv)
executes the program
boost::program_options::variables_map & OptionsMap()
get available program options & descriptions
boost::program_options::options_description & VisibleOptions()
filters out the Hidden group from the options descriptions
virtual std::string VersionString()
version string of application
Definition application.h:55
boost::program_options::options_description_easy_init AddProgramOptions(const std::string &group="")
add option for command line
void CheckRequired(const std::string &option_name, const std::string &error_msg="")
Check weather required option is set.
class to manage program options with xml serialization functionality
Definition property.h:55
Property & add(const std::string &key, const std::string &value)
add a new property to structure
Definition property.cc:108
Topology map(const csg::Topology &top) const
void WriteFrame(const Topology &top)
Definition statesaver.cc:44
Container for segments and box and atoms.
Definition topology.h:41
STL namespace.
FileFormatFactory< TopologyReader > & TopReaderFactory()
FileFormatFactory< TrajectoryReader > & TrjReaderFactory()
const double nm2ang
Definition constants.h:50
bool FileExists(const std::string &filename)
Definition filesystem.cc:50
Charge transport classes.
Definition ERIs.h:28
void HelpTextHeader(const std::string &tool_name)
Definition version.cc:34
Eigen::Index Index
Definition types.h:26
static bool verbose()
Definition globals.h:32
int main(int argc, char **argv)
Definition xtp_map.cc:404
void GuessBonds(CSG::Topology &top)
Definition xtp_map.cc:84
static const std::map< std::string, double > kBondiVdWRadiusAngstrom
Definition xtp_map.cc:67