Debian Codegraph @

avogadro/io/turbomoleformat.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "turbomoleformat.h"
7
8 #include <avogadro/core/elements.h>
9 #include <avogadro/core/molecule.h>
10 #include <avogadro/core/spacegroups.h>
11 #include <avogadro/core/unitcell.h>
12 #include <avogadro/core/utilities.h>
13 #include <avogadro/core/vector.h>
14
15 #include <nlohmann/json.hpp>
16
17 #include <iomanip>
18 #include <istream>
19 #include <optional>
20 #include <ostream>
21 #include <string>
22
23 using json = nlohmann::json;
24
25 using std::getline;
26 using std::string;
27
28 namespace Avogadro::Io {
29
30 using Core::Array;
31 using Core::Atom;
32 using Core::Elements;
33 using Core::lexicalCast;
34 using Core::rstrip;
35 using Core::SpaceGroups;
36 using Core::split;
37
38 #ifndef _WIN32
39 using std::isalpha;
40 #endif
41
42 bool TurbomoleFormat::read(std::istream& inStream, Core::Molecule& mol)
43 {
44 json opts;
45 if (!options().empty())
46 opts = json::parse(options(), nullptr, false);
47 else
48 opts = json::object();
49
50 bool hasCell = false;
51 bool hasLattice = false;
52 bool fractionalCoords = false;
53
54 // possible lattice constants
55 // if periodic is either one or two, the values are used for "vacuum"
56 Real a = 100.0, b = 100.0, c = 100.0;
57 Real alpha = 90.0 * DEG_TO_RAD, beta = 90.0 * DEG_TO_RAD,
58 gamma = 90.0 * DEG_TO_RAD;
59 // defaults if periodicity is not 3
60 Vector3 v1(100.0, 0.0, 0.0);
61 Vector3 v2(0.0, 100.0, 0.0);
62 Vector3 v3(0.0, 0.0, 100.0);
63 std::optional<unsigned> periodic_parsed, periodic_guessed;
64
65 // we loop through each line until we hit $end or EOF
66 string buffer;
67 getline(inStream, buffer);
68 while (inStream.good() && !buffer.empty()) {
69 std::vector<string> tokens = split(rstrip(buffer, '#'), ' ');
70 if (tokens.empty()) { // "# comment line"
71 getline(inStream, buffer);
72 continue;
73 }
74
75 if (tokens[0] == "$end")
76 break;
77
78 if (tokens[0] == "$periodic") {
79 if (tokens.size() != 2u) {
80 appendError("Not enough or extra tokens in this line: " + buffer);
81 return false;
82 }
83
84 if (auto tmp = lexicalCast<int>(tokens[1])) {
85 if (*tmp < 0 || *tmp > 3) {
86 appendError("Invalid dimensionality: " + buffer);
87 return false;
88 }
89 periodic_parsed = static_cast<unsigned>(*tmp);
90 } else {
91 appendError("Failed to parse: " + buffer);
92 return false;
93 }
94 getline(inStream, buffer);
95 continue;
96 }
97
98 if (tokens[0] == "$coord") {
99 // check if there's a conversion to be done
100 Real coordConversion = BOHR_TO_ANGSTROM; // default is Bohr
101 if (std::find(tokens.begin(), tokens.end(), "angs") != tokens.end())
102 coordConversion = 1.0; // leave as Angstrom
103 else if (std::find(tokens.begin(), tokens.end(), "frac") !=
104 tokens.end()) {
105 fractionalCoords = true;
106 coordConversion = 1.0; // we may not know the lattice constants yet
107 } else if (tokens.size() > 1u && tokens[1][0] != '#') {
108 std::cerr << "Ignore unknown trailing token and assume bohr: " << buffer
109 << '\n';
110 }
111
112 getline(inStream, buffer);
113 tokens = split(rstrip(buffer, '#'), ' ');
114 while (!tokens.empty() && tokens[0][0] != '$') {
115 // parse atoms until we see another '$' section
116 // e.g. 0.0000 0.000000 -0.73578 o
117
118 if (tokens.size() < 4) {
119 appendError("Not enough tokens in this line: " + buffer);
120 return false;
121 }
122
123 unsigned char atomicNum(0);
124 if (isalpha(tokens[3][0])) {
125 tokens[3][0] = toupper(tokens[3][0]);
126 atomicNum = Elements::atomicNumberFromSymbol(tokens[3]);
127 } else
128 atomicNum = static_cast<unsigned char>(
129 lexicalCast<short int>(tokens[3]).value_or(0));
130
131 Vector3 pos;
132 if (auto tmp =
133 lexicalCast<double>(tokens.begin(), tokens.begin() + 3)) {
134 pos << tmp->at(0), tmp->at(1), tmp->at(2);
135 } else {
136 appendError("Failed to parse this line following $coord: " + buffer);
137 return false;
138 }
139
140 Atom newAtom = mol.addAtom(atomicNum);
141 newAtom.setPosition3d(pos * coordConversion);
142
143 // next line
144 getline(inStream, buffer);
145 tokens = split(rstrip(buffer, '#'), ' ');
146 }
147 } else if (tokens[0] == "$cell") {
148 if (hasLattice) {
149 appendError("Both of $cell and $lattice are specified");
150 return false;
151 }
152 hasCell = true;
153 Real cellConversion = BOHR_TO_ANGSTROM;
154 if (std::find(tokens.begin(), tokens.end(), "angs") != tokens.end())
155 cellConversion = 1.0; // leave as Angstrom
156
157 getline(inStream, buffer);
158 tokens = split(rstrip(buffer, '#'), ' ');
159 const auto tokens_converted =
160 lexicalCast<double>(tokens.begin(), tokens.end());
161 if (!tokens_converted) {
162 appendError("Failed to parse: " + buffer);
163 return false;
164 }
165
166 const auto ntokens = tokens_converted->size();
167
168 auto set_cell_vars = [&](unsigned periodic) {
169 if (periodic == 1) {
170 a = tokens_converted->at(0) * cellConversion;
171 } else if (periodic == 2) {
172 a = tokens_converted->at(0) * cellConversion;
173 b = tokens_converted->at(1) * cellConversion;
174 gamma = tokens_converted->at(2) * DEG_TO_RAD;
175 } else {
176 a = tokens_converted->at(0) * cellConversion;
177 b = tokens_converted->at(1) * cellConversion;
178 c = tokens_converted->at(2) * cellConversion;
179 alpha = tokens_converted->at(3) * DEG_TO_RAD;
180 beta = tokens_converted->at(4) * DEG_TO_RAD;
181 gamma = tokens_converted->at(5) * DEG_TO_RAD;
182 }
183 };
184
185 if (periodic_parsed) {
186 // $periodic appeared
187 if ((*periodic_parsed == 1 && ntokens == 1) ||
188 (*periodic_parsed == 2 && ntokens == 3) ||
189 (*periodic_parsed == 3 && ntokens == 6)) {
190 set_cell_vars(*periodic_parsed);
191 } else if (*periodic_parsed == 0) {
192 hasCell = false;
193 std::cerr << "Ignore $cell since '$periodic 0' (non periodic) "
194 "is specified\n";
195 } else {
196 appendError("Not enough or extra tokens in this line: " + buffer);
197 return false;
198 }
199 } else {
200 // $periodic does not appear yet, so guess it from the number of the
201 // elements
202 if (ntokens == 1) {
203 periodic_guessed = 1;
204 } else if (ntokens == 3) {
205 periodic_guessed = 2;
206 } else if (ntokens == 6) {
207 periodic_guessed = 3;
208 } else {
209 appendError("Cannot determine dimensionality from $cell: " + buffer);
210 return false;
211 }
212 set_cell_vars(*periodic_guessed);
213 }
214
215 } else if (tokens[0] == "$lattice") {
216 if (hasCell) {
217 appendError("Both of $cell and $lattice are specified");
218 return false;
219 }
220 hasLattice = true;
221 Real latticeConversion = BOHR_TO_ANGSTROM; // default
222 if (std::find(tokens.begin(), tokens.end(), "angs") != tokens.end())
223 latticeConversion = 1.0; // leave as Angstrom
224
225 if (periodic_parsed) {
226 // $periodic appeared
227 if (*periodic_parsed == 0) {
228 hasLattice = false;
229 std::cerr << "Ignore $lattice since '$periodic 0' (non periodic) "
230 "is specified\n";
231 }
232
233 for (unsigned line = 0; line < *periodic_parsed; ++line) {
234 getline(inStream, buffer);
235 tokens = split(rstrip(buffer, '#'), ' ');
236 const auto tmp = lexicalCast<double>(tokens.begin(), tokens.end());
237 if (!tmp) {
238 appendError("Failed to parse this line following $lattice: " +
239 buffer);
240 return false;
241 }
242 if (tmp->size() != *periodic_parsed) {
243 appendError(
244 "Not enough or extra tokens in this line following $lattice: " +
245 buffer);
246 return false;
247 }
248
249 if (line == 0) {
250 v1.x() = tmp->at(0) * latticeConversion;
251 v1.y() =
252 *periodic_parsed == 1 ? 0.0 : tmp->at(1) * latticeConversion;
253 v1.z() =
254 *periodic_parsed < 3 ? 0.0 : tmp->at(2) * latticeConversion;
255 } else if (line == 1) {
256 v2.x() = tmp->at(0) * latticeConversion;
257 v2.y() = tmp->at(1) * latticeConversion;
258 v2.z() =
259 *periodic_parsed < 3 ? 0.0 : tmp->at(2) * latticeConversion;
260 } else if (line == 2) {
261 v3.x() = tmp->at(0) * latticeConversion;
262 v3.y() = tmp->at(1) * latticeConversion;
263 v3.z() = tmp->at(2) * latticeConversion;
264 }
265 }
266 } else {
267 // $periodic does not appear yet, so guess dimensionality from line(s)
268 // following $lattice
269 for (unsigned line = 0; line < 3; ++line) {
270 getline(inStream, buffer);
271 tokens = split(rstrip(buffer, '#'), ' ');
272 const auto tmp = lexicalCast<double>(tokens.begin(), tokens.end());
273 if (!tmp) {
274 appendError("Failed to parse: " + buffer);
275 return false;
276 }
277
278 const auto n = tmp->size();
279 if (line == 0) {
280 if (n == 0u || n > 3u) {
281 appendError("Could not determine dimensionality from lines "
282 "following $lattice:\n" +
283 buffer);
284 return false;
285 }
286 periodic_guessed = n;
287 } else if (*periodic_guessed != n) {
288 appendError("The previous and current lines respectively have " +
289 std::to_string(*periodic_guessed) + " and " +
290 std::to_string(n) + " element(s)\n" + buffer);
291 return false;
292 }
293
294 if (line == 0) {
295 v1.x() = tmp->at(0) * latticeConversion;
296 if (n < 2)
297 break;
298 v1.y() = tmp->at(1) * latticeConversion;
299 v1.z() = n != 3 ? 0.0 : tmp->at(2) * latticeConversion;
300 } else if (line == 1) {
301 v2.x() = tmp->at(0) * latticeConversion;
302 v2.y() = tmp->at(1) * latticeConversion;
303 if (n < 3)
304 break;
305 v2.z() = tmp->at(2) * latticeConversion;
306 } else if (line == 2) {
307 v3.x() = tmp->at(0) * latticeConversion;
308 v3.y() = tmp->at(1) * latticeConversion;
309 v3.z() = tmp->at(2) * latticeConversion;
310 }
311 }
312 }
313
314 } else if (tokens[0][0] != '#') {
315 std::cerr << "Ignore unknown token: " << buffer << '\n';
316 }
317
318 getline(inStream, buffer);
319 } // done reading the file
320
321 if (periodic_parsed && *periodic_parsed > 0 && (!hasLattice && !hasCell)) {
322 appendError("$periodic specifies " + std::to_string(*periodic_parsed) +
323 " but neither $cell nor $lattice appears");
324 return false;
325 }
326
327 if (periodic_parsed && periodic_guessed &&
328 *periodic_parsed != *periodic_guessed) {
329 appendError("Dimensionality guessed from $lattice/$cell is " +
330 std::to_string(*periodic_guessed) +
331 " but $periodic specifies " + std::to_string(*periodic_parsed));
332 return false;
333 }
334
335 Core::UnitCell* cell = nullptr;
336 std::string tmp;
337 if (hasLattice) {
338 cell = new Core::UnitCell(v1, v2, v3);
339 tmp = "$lattice";
340 } else if (hasCell) {
341 cell = new Core::UnitCell(a, b, c, alpha, beta, gamma);
342 tmp = "$cell";
343 }
344 if (cell) {
345 if (!cell->isRegular()) {
346 appendError(tmp + " does not give linear independent lattice vectors");
347 delete cell;
348 return false;
349 }
350 mol.setUnitCell(cell);
351 }
352
353 // if we have fractional coordinates, we need to convert them to cartesian
354 if (fractionalCoords) {
355 auto* cell = mol.unitCell();
356 for (Index i = 0; i < mol.atomCount(); ++i) {
357 mol.setAtomPosition3d(i, cell->toCartesian(mol.atomPosition3d(i)));
358 }
359 }
360
361 // This format has no connectivity information, so perceive basics at least.
362 if (opts.value("perceiveBonds", true)) {
363 mol.perceiveBondsSimple();
364 mol.perceiveBondOrders();
365 }
366
367 return true;
368 }
369
370 bool TurbomoleFormat::write(std::ostream& outStream, const Core::Molecule& mol)
371 {
372 // Filter out translational duplicates if there's a unit cell
373 Array<Index> uniqueIndices = SpaceGroups::translationalUniqueAtoms(mol);
374 if (uniqueIndices.empty()) {
375 // No unit cell or no filtering needed - use all atoms
376 for (Index i = 0; i < mol.atomCount(); ++i)
377 uniqueIndices.push_back(i);
378 }
379
380 // convert to Bohr because some programs can't handle Angstrom
381 outStream << "$coord\n";
382
383 // print $isosub only when an isotope exists
384 std::ostringstream isosub;
385
386 Index outputIdx = 0;
387 for (Index atomIdx : uniqueIndices) {
388 Atom atom = mol.atom(atomIdx);
389 if (!atom.isValid()) {
390 appendError("Internal error: Atom invalid.");
391 return false;
392 }
393
394 std::string symbol = Elements::symbol(atom.atomicNumber());
395 symbol[0] = tolower(symbol[0]);
396
397 Vector3 position = atom.position3d() * ANGSTROM_TO_BOHR;
398 outStream << " " << std::setw(18) << std::right << std::fixed
399 << std::setprecision(10) << position.x() << " " << std::setw(18)
400 << std::right << std::fixed << std::setprecision(10)
401 << position.y() << " " << std::setw(18) << std::right
402 << std::fixed << std::setprecision(10) << position.z() << " "
403 << std::setw(5) << std::right << symbol << "\n";
404 auto iso = mol.isotope(atomIdx);
405 if (iso > 0)
406 isosub << (outputIdx + 1) << " " << iso << '\n';
407 ++outputIdx;
408 }
409
410 if (auto s = isosub.str(); !s.empty()) {
411 outStream << "$isosub\n" << s;
412 }
413
414 if (mol.unitCell()) {
415 outStream << "$periodic 3\n";
416 outStream << "$lattice angs\n";
417 outStream << mol.unitCell()->aVector().x() << ' ';
418 outStream << mol.unitCell()->aVector().y() << ' ';
419 outStream << mol.unitCell()->aVector().z() << '\n';
420
421 outStream << mol.unitCell()->bVector().x() << ' ';
422 outStream << mol.unitCell()->bVector().y() << ' ';
423 outStream << mol.unitCell()->bVector().z() << '\n';
424
425 outStream << mol.unitCell()->cVector().x() << ' ';
426 outStream << mol.unitCell()->cVector().y() << ' ';
427 outStream << mol.unitCell()->cVector().z() << '\n';
428 }
429
430 outStream << "$end\n";
431
432 return true;
433 }
434
435 std::vector<std::string> TurbomoleFormat::fileExtensions() const
436 {
437 std::vector<std::string> ext;
438 ext.emplace_back("coord");
439 ext.emplace_back("tmol");
440 return ext;
441 }
442
443 std::vector<std::string> TurbomoleFormat::mimeTypes() const
444 {
445 std::vector<std::string> mime;
446 mime.emplace_back("chemical/x-turbomole");
447 return mime;
448 }
449
450 } // namespace Avogadro::Io