Debian Codegraph @

avogadro/io/vaspformat.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 "vaspformat.h"
7
8 #include <avogadro/core/elements.h> // for atomicNumberFromSymbol()
9 #include <avogadro/core/matrix.h> // for matrix3
10 #include <avogadro/core/molecule.h>
11 #include <avogadro/core/spacegroups.h> // for translationalUniqueAtoms()
12 #include <avogadro/core/unitcell.h>
13 #include <avogadro/core/utilities.h> // for split(), trimmed(), lexicalCast()
14 #include <avogadro/core/vector.h> // for Vector3
15
16 #include <algorithm> // for std::count()
17 #include <iomanip>
18 #include <iostream>
19
20 namespace Avogadro::Io {
21
22 using std::getline;
23 using std::map;
24 using std::string;
25
26 using Core::Array;
27 using Core::Atom;
28 using Core::Elements;
29 using Core::lexicalCast;
30 using Core::Molecule;
31 using Core::SpaceGroups;
32 using Core::split;
33 using Core::trimmed;
34 using Core::UnitCell;
35
36 bool PoscarFormat::read(std::istream& inStream, Core::Molecule& mol)
37 {
38 size_t numLines = std::count(std::istreambuf_iterator<char>(inStream),
39 std::istreambuf_iterator<char>(), '\n');
40
41 // There must be at least 7 "\n"'s to have a minimum crystal (including 1
42 // atom)
43 if (numLines < 7) {
44 appendError("Error: POSCAR file is 7 or fewer lines long");
45 return false;
46 }
47
48 // We have to go back to the beginning if we are going to read again
49 inStream.clear();
50 inStream.seekg(0, std::ios::beg);
51
52 // We'll use these throughout
53 bool ok;
54 string line;
55 std::vector<string> stringSplit;
56
57 // First line is comment line
58 getline(inStream, line);
59 line = trimmed(line);
60 string title = " ";
61 if (!line.empty())
62 title = line;
63
64 // Next line is scaling factor
65 getline(inStream, line);
66 const auto scalingFactor = lexicalCast<double>(line);
67
68 if (!scalingFactor) {
69 appendError("Error: Could not convert scaling factor to double in POSCAR");
70 return false;
71 }
72
73 Matrix3 cellMat;
74
75 // Next comes the matrix
76 for (size_t i = 0; i < 3; ++i) {
77 getline(inStream, line);
78 stringSplit = split(line, ' ');
79 // If this is not three, then there is some kind of error in the line
80 if (stringSplit.size() != 3) {
81 appendError("Error reading lattice vectors in POSCAR");
82 return false;
83 }
84 // UnitCell expects a matrix of this form
85 if (auto tmp =
86 lexicalCast<double>(stringSplit.begin(), stringSplit.end())) {
87 cellMat(0, i) = tmp->at(0) * *scalingFactor;
88 cellMat(1, i) = tmp->at(1) * *scalingFactor;
89 cellMat(2, i) = tmp->at(2) * *scalingFactor;
90 } else {
91 appendError("Error reading a lattice vector");
92 return false;
93 }
94 }
95
96 // Sometimes, atomic symbols go here.
97 getline(inStream, line);
98 stringSplit = split(line, ' ');
99
100 if (stringSplit.empty()) {
101 appendError("Error reading numbers of atom types in POSCAR");
102 return false;
103 }
104
105 // Try a lexical cast here. If it fails, assume we have an atomic symbols list
106 lexicalCast<unsigned int>(trimmed(stringSplit.at(0)), ok);
107 std::vector<string> symbolsList;
108 std::vector<unsigned char> atomicNumbers;
109
110 if (!ok) {
111 // Assume atomic symbols are here and store them
112 symbolsList = split(line, ' ');
113 // Store atomic nums (trim to handle Windows CRLF line endings)
114 for (auto& i : symbolsList)
115 atomicNumbers.push_back(Elements::atomicNumberFromSymbol(trimmed(i)));
116 // This next one should be atom types
117 getline(inStream, line);
118 }
119 // If the atomic symbols aren't here, try to find them in the title
120 // In Vasp 4.x, symbols are in the title like so: " O4H2 <restOfTitle>"
121 else {
122 stringSplit = split(title, ' ');
123 if (stringSplit.size() != 0) {
124 string trimmedFormula = trimmed(stringSplit.at(0));
125 // Let's replace all numbers with spaces
126 for (char& i : trimmedFormula) {
127 if (isdigit(i))
128 i = ' ';
129 }
130 // Now get the symbols with a simple space split
131 symbolsList = split(trimmedFormula, ' ');
132 for (auto& i : symbolsList)
133 atomicNumbers.push_back(Elements::atomicNumberFromSymbol(i));
134 }
135 }
136
137 stringSplit = split(line, ' ');
138 std::vector<unsigned int> atomCounts;
139 if (auto tmp =
140 lexicalCast<unsigned int>(stringSplit.begin(), stringSplit.end())) {
141 atomCounts = std::move(*tmp);
142 } else {
143 appendError("Error reading numbers of atoms: " + line);
144 return false;
145 }
146
147 // If we never filled up the atomic numbers, fill them up
148 // now with "1, 2, 3…"
149 if (atomicNumbers.size() == 0)
150 for (size_t i = 1; i <= atomCounts.size(); ++i)
151 atomicNumbers.push_back(i);
152
153 if (atomicNumbers.size() != atomCounts.size()) {
154 appendError("Error: numSymbols and numTypes are not equal in POSCAR!");
155 return false;
156 }
157
158 // Starts with either [Ss]elective dynamics, [KkCc]artesian, or
159 // other for fractional coords.
160 getline(inStream, line);
161 line = trimmed(line);
162
163 // If selective dynamics, get the next line
164 if (line.empty() || line.at(0) == 'S' || line.at(0) == 's')
165 getline(inStream, line);
166
167 line = trimmed(line);
168 if (line.empty()) {
169 appendError("Error determining Direct or Cartesian in POSCAR");
170 return false;
171 }
172
173 bool cart;
174 // Check if we're using cartesian or fractional coordinates:
175 if (line.at(0) == 'K' || line.at(0) == 'k' || line.at(0) == 'C' ||
176 line.at(0) == 'c') {
177 cart = true;
178 }
179 // Assume direct if one of these was not found
180 else {
181 cart = false;
182 }
183
184 std::vector<Vector3> atoms;
185 for (unsigned int atomCount : atomCounts) {
186 for (size_t j = 0; j < atomCount; ++j) {
187 getline(inStream, line);
188 stringSplit = split(line, ' ');
189 // This may be greater than 3 with selective dynamics
190 if (stringSplit.size() < 3) {
191 appendError("Error reading atomic coordinates in POSCAR");
192 return false;
193 }
194 if (auto tmp =
195 lexicalCast<double>(stringSplit.begin(), stringSplit.begin() + 3)) {
196 atoms.emplace_back(tmp->at(0), tmp->at(1), tmp->at(2));
197 } else {
198 appendError("Error reading atomic coordinates in POSCAR");
199 return false;
200 }
201 }
202 }
203
204 // Let's make a unit cell
205 auto* cell = new UnitCell(cellMat);
206
207 if (!cell->isRegular()) {
208 appendError("cell vectors are not linear independent");
209 delete cell;
210 return false;
211 }
212
213 // If our atomic coordinates are fractional, convert them to Cartesian
214 if (!cart) {
215 for (auto& atom : atoms)
216 atom = cell->toCartesian(atom);
217 }
218 // If they're cartesian, we just need to apply the scaling factor
219 else {
220 for (auto& atom : atoms)
221 atom *= *scalingFactor;
222 }
223
224 // If we made it this far, the read was a success!
225 // Delete the current molecule. Add the new title and unit cell
226 mol.clearAtoms();
227 mol.setData("name", title);
228 mol.setUnitCell(cell);
229
230 // Now add the atoms
231 size_t k = 0;
232 for (size_t i = 0; i < atomCounts.size(); ++i) {
233 unsigned char atomicNum = atomicNumbers.at(i);
234 for (size_t j = 0; j < atomCounts.at(i); ++j) {
235 Atom newAtom = mol.addAtom(atomicNum);
236 newAtom.setPosition3d(atoms.at(k));
237 ++k;
238 }
239 }
240
241 return true;
242 }
243
244 bool PoscarFormat::write(std::ostream& outStream, const Core::Molecule& mol)
245 {
246 // Title
247 if (mol.data("name").toString().length())
248 outStream << mol.data("name").toString() << std::endl;
249 else
250 outStream << "POSCAR" << std::endl;
251
252 // Scaling factor
253 outStream << " 1.00000000" << std::endl;
254
255 // 3x3 matrix. Transpose is needed to orient the matrix correctly.
256 const Matrix3& mat = mol.unitCell()->cellMatrix().transpose();
257 for (size_t i = 0; i < 3; ++i) {
258 for (size_t j = 0; j < 3; ++j) {
259 outStream << " " << std::setw(10) << std::right << std::fixed
260 << std::setprecision(8) << mat(i, j);
261 }
262 outStream << std::endl;
263 }
264
265 // Filter out translational duplicates (atoms at ~1.0 that duplicate ~0.0)
266 Array<Index> uniqueIndices = SpaceGroups::translationalUniqueAtoms(mol);
267
268 // Build composition from filtered atoms only
269 std::map<unsigned char, size_t> composition;
270 for (Index idx : uniqueIndices) {
271 composition[mol.atomicNumber(idx)]++;
272 }
273
274 // Atom symbols
275 auto iter = composition.begin();
276 while (iter != composition.end()) {
277 outStream << " " << Elements::symbol(iter->first);
278 ++iter;
279 }
280 outStream << std::endl;
281
282 // Numbers of each type
283 iter = composition.begin();
284 while (iter != composition.end()) {
285 outStream << " " << iter->second;
286 ++iter;
287 }
288 outStream << std::endl;
289
290 // Direct or cartesian?
291 outStream << "Direct" << std::endl;
292
293 // Final section is atomic coordinates
294 // We need to make sure we group the atomic numbers together.
295 // The outer loop is for grouping them.
296 iter = composition.begin();
297 while (iter != composition.end()) {
298 unsigned char currentAtomicNum = iter->first;
299 for (Index idx : uniqueIndices) {
300 // We need to group atomic numbers together. If this one is not
301 // the current atomic number, skip over it.
302 if (mol.atomicNumber(idx) != currentAtomicNum)
303 continue;
304
305 Atom atom = mol.atom(idx);
306 if (!atom.isValid()) {
307 appendError("Internal error: Atom invalid.");
308 return false;
309 }
310 Vector3 fracCoords = mol.unitCell()->toFractional(atom.position3d());
311 outStream << " " << std::setw(10) << std::right << std::fixed
312 << std::setprecision(8) << fracCoords.x() << " "
313 << std::setw(10) << std::right << std::fixed
314 << std::setprecision(8) << fracCoords.y() << " "
315 << std::setw(10) << std::right << std::fixed
316 << std::setprecision(8) << fracCoords.z() << "\n";
317 }
318 ++iter;
319 }
320
321 return true;
322 }
323
324 std::vector<std::string> PoscarFormat::fileExtensions() const
325 {
326 std::vector<std::string> ext;
327 ext.emplace_back("POSCAR");
328 ext.emplace_back("CONTCAR");
329 ext.emplace_back("vasp");
330 return ext;
331 }
332
333 std::vector<std::string> PoscarFormat::mimeTypes() const
334 {
335 std::vector<std::string> mime;
336 mime.emplace_back("N/A");
337 return mime;
338 }
339
340 bool OutcarFormat::read(std::istream& inStream, Core::Molecule& mol)
341 {
342 std::string buffer, dashedStr, positionStr, latticeStr, directLatticeStr;
343 positionStr = " POSITION";
344 latticeStr = " Lattice vectors:";
345 directLatticeStr = " direct lattice vectors"; // VASP 6.x format
346 dashedStr = " -----------";
347 std::string vrhfinStr = " VRHFIN =";
348 std::string ionsPerTypeStr = " ions per type =";
349 std::vector<std::string> stringSplit;
350 int coordSet = 0, natoms = 0;
351 Array<Vector3> positions;
352 Vector3 ax1, ax2, ax3;
353 bool ax1Set = false, ax2Set = false, ax3Set = false;
354
355 // Element type information parsed from VRHFIN and "ions per type" lines
356 std::vector<unsigned char> elementTypes; // atomic numbers from VRHFIN
357 std::vector<unsigned int> atomCounts; // counts from "ions per type"
358
359 typedef map<string, unsigned char> AtomTypeMap;
360 AtomTypeMap atomTypes;
361 unsigned char customElementCounter = CustomElementMin;
362
363 while (getline(inStream, buffer)) {
364 // Parse VRHFIN lines to get element symbols (e.g., " VRHFIN =C: s2p2")
365 if (buffer.substr(0, vrhfinStr.size()) == vrhfinStr) {
366 // Extract element symbol between '=' and ':'
367 size_t startPos = buffer.find('=');
368 size_t endPos = buffer.find(':');
369 if (startPos != std::string::npos && endPos != std::string::npos &&
370 endPos > startPos + 1) {
371 std::string symbol =
372 trimmed(buffer.substr(startPos + 1, endPos - startPos - 1));
373 unsigned char atomicNum = Elements::atomicNumberFromSymbol(symbol);
374 if (atomicNum != Avogadro::InvalidElement) {
375 elementTypes.push_back(atomicNum);
376 }
377 }
378 }
379
380 // Parse "ions per type" line to get atom counts (e.g., " ions per type =
381 // 48 24 26 8")
382 else if (buffer.substr(0, ionsPerTypeStr.size()) == ionsPerTypeStr) {
383 std::string countsStr = buffer.substr(ionsPerTypeStr.size());
384 stringSplit = split(countsStr, ' ');
385 for (const auto& countStr : stringSplit) {
386 if (auto count = lexicalCast<unsigned int>(countStr)) {
387 atomCounts.push_back(*count);
388 }
389 }
390 }
391
392 // Checks whether the buffer object contains the lattice vectors keyword
393 else if (buffer.substr(0, latticeStr.size()) == latticeStr) {
394 // Checks whether lattice vectors have been already set. Reason being that
395 // only the first occurrence denotes the true lattice vectors, and the
396 // ones following these are vectors of the primitive cell.
397 if (!(ax1Set && ax2Set && ax3Set)) {
398 getline(inStream, buffer);
399 for (int i = 0; i < 3; ++i) {
400 getline(inStream, buffer);
401 stringSplit = split(buffer, ' ');
402
403 auto x = lexicalCast<double>(
404 stringSplit.at(3).substr(0, stringSplit.at(3).size() - 1));
405 auto y = lexicalCast<double>(
406 stringSplit.at(4).substr(0, stringSplit.at(4).size() - 1));
407 auto z = lexicalCast<double>(
408 stringSplit.at(5).substr(0, stringSplit.at(5).size() - 1));
409
410 if (!x || !y || !z) {
411 appendError("Error reading a lattice vector");
412 return false;
413 }
414 Vector3 tmp(*x, *y, *z);
415
416 if (stringSplit[0] == "A1") {
417 ax1 = std::move(tmp);
418 ax1Set = true;
419 } else if (stringSplit[0] == "A2") {
420 ax2 = std::move(tmp);
421 ax2Set = true;
422 } else if (stringSplit[0] == "A3") {
423 ax3 = std::move(tmp);
424 ax3Set = true;
425 }
426 }
427 // Checks whether all the three axis vectors have been read
428 if (ax1Set && ax2Set && ax3Set) {
429 auto* cell = new UnitCell(ax1, ax2, ax3);
430 if (!cell->isRegular()) {
431 appendError("cell vectors are not linear independent");
432 return false;
433 }
434 mol.setUnitCell(cell);
435 }
436 }
437 }
438
439 // VASP 6.x format: " direct lattice vectors" with fixed-width columns
440 else if (buffer.substr(0, directLatticeStr.size()) == directLatticeStr) {
441 if (!(ax1Set && ax2Set && ax3Set)) {
442 // Read 3 lines of lattice vectors (fixed-width: 13 chars per value,
443 // starting at position 3)
444 Vector3 axes[3];
445 bool parseOk = true;
446 for (int i = 0; i < 3 && parseOk; ++i) {
447 getline(inStream, buffer);
448 if (buffer.size() >= 42) { // Need at least 3 + 13*3 = 42 characters
449 auto x = lexicalCast<double>(trimmed(buffer.substr(3, 13)));
450 auto y = lexicalCast<double>(trimmed(buffer.substr(16, 13)));
451 auto z = lexicalCast<double>(trimmed(buffer.substr(29, 13)));
452 if (x && y && z) {
453 axes[i] = Vector3(*x, *y, *z);
454 } else {
455 parseOk = false;
456 }
457 } else {
458 parseOk = false;
459 }
460 }
461 if (parseOk) {
462 ax1 = axes[0];
463 ax1Set = true;
464 ax2 = axes[1];
465 ax2Set = true;
466 ax3 = axes[2];
467 ax3Set = true;
468 auto* cell = new UnitCell(ax1, ax2, ax3);
469 if (!cell->isRegular()) {
470 appendError("cell vectors are not linear independent");
471 return false;
472 }
473 mol.setUnitCell(cell);
474 }
475 }
476 }
477
478 // Checks whether the buffer object contains the POSITION keyword
479 else if (buffer.substr(0, positionStr.size()) == positionStr) {
480 getline(inStream, buffer);
481 // Double checks whether the succeeding line is a sequence of dashes
482 if (buffer.substr(0, dashedStr.size()) == dashedStr) {
483 // natoms is not known, so the loop proceeds till the bottom dashed line
484 // is encountered
485 while (true) {
486 getline(inStream, buffer);
487 // Condition for encountering dashed line
488 if (buffer.substr(0, dashedStr.size()) == dashedStr) {
489 if (coordSet == 0) {
490 mol.setCoordinate3d(mol.atomPositions3d(), coordSet++);
491 positions.reserve(natoms);
492 } else {
493 mol.setCoordinate3d(positions, coordSet++);
494 positions.clear();
495 }
496 break;
497 }
498 // Parsing the coordinates
499 stringSplit = split(buffer, ' ');
500 Vector3 tmpAtom;
501 if (auto tmp = lexicalCast<double>(stringSplit.begin(),
502 stringSplit.begin() + 3)) {
503 tmpAtom << tmp->at(0), tmp->at(1), tmp->at(2);
504 } else {
505 appendError("Error reading atom position");
506 return false;
507 }
508 if (coordSet == 0) {
509 unsigned char atomicNum;
510 // Check if we have valid element type information
511 if (!elementTypes.empty() &&
512 elementTypes.size() == atomCounts.size()) {
513 // Determine which element type this atom belongs to based on
514 // cumulative counts
515 unsigned int cumulative = 0;
516 atomicNum = elementTypes.back(); // default to last element
517 for (size_t i = 0; i < atomCounts.size(); ++i) {
518 cumulative += atomCounts[i];
519 if (static_cast<unsigned int>(natoms) < cumulative) {
520 atomicNum = elementTypes[i];
521 break;
522 }
523 }
524 } else {
525 // Fall back to custom elements if element info not available
526 AtomTypeMap::const_iterator it;
527 atomTypes.insert(
528 std::make_pair(std::to_string(natoms), customElementCounter++));
529 it = atomTypes.find(std::to_string(natoms));
530 atomicNum = it->second;
531 }
532 Atom newAtom = mol.addAtom(atomicNum);
533 newAtom.setPosition3d(tmpAtom);
534 natoms++;
535 } else {
536 positions.push_back(tmpAtom);
537 }
538 }
539 }
540 }
541 }
542
543 // Set the custom element map if needed:
544 if (!atomTypes.empty()) {
545 Molecule::CustomElementMap elementMap;
546 for (const auto& atomType : atomTypes) {
547 elementMap.insert(
548 std::make_pair(atomType.second, "Atom " + atomType.first));
549 }
550 mol.setCustomElementMap(elementMap);
551 }
552
553 return true;
554 }
555
556 bool OutcarFormat::write(std::ostream&, const Core::Molecule&)
557 {
558 return false;
559 }
560
561 std::vector<std::string> OutcarFormat::fileExtensions() const
562 {
563 std::vector<std::string> ext;
564 ext.emplace_back("OUTCAR");
565 return ext;
566 }
567
568 std::vector<std::string> OutcarFormat::mimeTypes() const
569 {
570 std::vector<std::string> mime;
571 mime.emplace_back("N/A");
572 return mime;
573 }
574
575 } // namespace Avogadro::Io