Debian Codegraph @

avogadro/io/cmlformat.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 "cmlformat.h"
7
8 #ifdef AVO_USE_HDF5
9 #include "hdf5dataformat.h"
10 #endif
11
12 #include <avogadro/core/crystaltools.h>
13 #include <avogadro/core/elements.h>
14 #include <avogadro/core/matrix.h>
15 #include <avogadro/core/molecule.h>
16 #include <avogadro/core/spacegroups.h>
17 #include <avogadro/core/unitcell.h>
18 #include <avogadro/core/utilities.h>
19
20 #include <pugixml.hpp>
21
22 #include <bitset>
23 #include <fstream>
24 #include <locale>
25 #include <map>
26 #include <sstream>
27
28 namespace Avogadro::Io {
29
30 using std::string;
31 using namespace std::string_literals;
32
33 using pugi::xml_attribute;
34 using pugi::xml_document;
35 using pugi::xml_node;
36
37 using namespace Core;
38
39 namespace {
40
41 class CmlFormatPrivate
42 {
43 public:
44 CmlFormatPrivate(Molecule* mol, xml_document& document, std::string filename_)
45 : success(false), molecule(mol), moleculeNode(nullptr), filename(filename_)
46 {
47 // Parse the CML document, and create molecules/elements as necessary.
48 moleculeNode = document.child("molecule");
49 xml_node cmlNode = document.child("cml");
50 if (cmlNode)
51 moleculeNode = cmlNode.child("molecule");
52
53 if (moleculeNode) {
54 // Parse the various components we know about.
55 #ifdef AVO_USE_HDF5
56 data();
57 #endif
58 success = properties();
59 if (success)
60 success = atoms();
61 if (success)
62 success = bonds();
63 } else {
64 error += "Error, no molecule node found.";
65 success = false;
66 }
67 }
68
69 bool properties()
70 {
71 xml_attribute attribute;
72 xml_node node;
73 node = moleculeNode.child("name");
74 if (node && node.value())
75 molecule->setData("name", std::string(node.child_value()));
76 node = moleculeNode.child("identifier");
77 if (node && node.value()) {
78 attribute = node.attribute("convention");
79 if (attribute && std::string(attribute.value()) == "iupac:inchi") {
80 attribute = node.attribute("value");
81 if (attribute && std::string(attribute.name()) == "value")
82 molecule->setData("inchi", std::string(attribute.value()));
83 }
84 }
85
86 // Unit cell:
87 node = moleculeNode.child("crystal");
88 if (node) {
89 float a(0);
90 float b(0);
91 float c(0);
92 float alpha(0);
93 float beta(0);
94 float gamma(0);
95 enum
96 {
97 CellA = 0,
98 CellB,
99 CellC,
100 CellAlpha,
101 CellBeta,
102 CellGamma
103 };
104 std::bitset<6> parsedValues;
105 for (pugi::xml_node scalar = node.child("scalar"); scalar;
106 scalar = scalar.next_sibling("scalar")) {
107 pugi::xml_attribute title = scalar.attribute("title");
108 if (title) {
109 std::string titleStr(title.value());
110 if (titleStr == "a") {
111 a = scalar.text().as_float();
112 parsedValues.set(CellA);
113 } else if (titleStr == "b") {
114 b = scalar.text().as_float();
115 parsedValues.set(CellB);
116 } else if (titleStr == "c") {
117 c = scalar.text().as_float();
118 parsedValues.set(CellC);
119 } else if (titleStr == "alpha") {
120 alpha = scalar.text().as_float() * DEG_TO_RAD_F;
121 parsedValues.set(CellAlpha);
122 } else if (titleStr == "beta") {
123 beta = scalar.text().as_float() * DEG_TO_RAD_F;
124 parsedValues.set(CellBeta);
125 } else if (titleStr == "gamma") {
126 gamma = scalar.text().as_float() * DEG_TO_RAD_F;
127 parsedValues.set(CellGamma);
128 }
129 }
130 }
131 if (parsedValues.count() != 6) {
132 error += "Incomplete unit cell description.";
133 return false;
134 }
135
136 // look for space group, e.g.
137 // <symmetry spaceGroup="F -4 2 3">
138 xml_node symmetry = node.child("symmetry");
139 unsigned short hall = 0;
140 if (symmetry) {
141 xml_attribute spaceGroup = symmetry.attribute("spaceGroup");
142 if (spaceGroup) {
143 // look for space group in the space group table
144 hall = Core::SpaceGroups::hallNumber(std::string(spaceGroup.value()));
145 }
146 }
147
148 auto* cell = new UnitCell;
149 cell->setCellParameters(a, b, c, alpha, beta, gamma);
150 if (!cell->isRegular()) {
151 error += "<crystal> does not give linear independent lattice vectors";
152 delete cell;
153 return false;
154 }
155 molecule->setUnitCell(cell);
156 if (hall != 0)
157 molecule->setHallNumber(hall);
158 }
159 return true;
160 }
161
162 bool atoms()
163 {
164 xml_node atomArray = moleculeNode.child("atomArray");
165 if (!atomArray)
166 return false;
167
168 xml_node node = atomArray.child("atom");
169 Atom atom;
170 while (node) {
171 // Step through all of the atom attributes and store them.
172 {
173 /* Element Attribute Check */
174 xml_attribute elementAtt = node.attribute("elementType");
175 if (elementAtt) {
176 unsigned char atomicNumber =
177 Elements::atomicNumberFromSymbol(elementAtt.value());
178 atom = molecule->addAtom(atomicNumber);
179 } else {
180 // There is no element data, this atom node is corrupt.
181 error += "Warning, corrupt element node found.";
182 return false;
183 }
184 }
185
186 {
187 /* ID Attribute Check */
188 xml_attribute idAtt = node.attribute("id");
189 if (idAtt)
190 atomIds[std::string(idAtt.value())] = atom.index();
191 else // Atom nodes must have IDs - bail.
192 return false;
193 }
194
195 // Check for 3D geometry.
196 {
197 /* XYZ3 and Fract Attribute Check */
198 xml_attribute x3Att = node.attribute("x3");
199 xml_attribute xFractAtt = node.attribute("xFract");
200 if (x3Att) {
201 xml_attribute y3 = node.attribute("y3");
202 xml_attribute z3 = node.attribute("z3");
203 if (y3 && z3) {
204 auto x = lexicalCast<double>(x3Att.value());
205 auto y = lexicalCast<double>(y3.value());
206 auto z = lexicalCast<double>(z3.value());
207 if (x && y && z) {
208 // It looks like we have a valid 3D position.
209 Vector3 position(*x, *y, *z);
210 atom.setPosition3d(position);
211 } else {
212 error += "x3, y3 or z3 attribute is malformed: ["s +
213 x3Att.value() + ", "s + y3.value() + ", "s + z3.value() +
214 "]."s;
215 return false;
216 }
217 } else {
218 // Corrupt 3D position supplied for atom.
219 return false;
220 }
221 } else if (xFractAtt) {
222 if (!molecule->unitCell()) {
223 error += "No unit cell defined. "
224 "Cannot interpret fractional coordinates.";
225 return false;
226 }
227 xml_attribute yF = node.attribute("yFract");
228 xml_attribute zF = node.attribute("zFract");
229 if (yF && zF) {
230 Vector3 coord(static_cast<Real>(xFractAtt.as_float()),
231 static_cast<Real>(yF.as_float()),
232 static_cast<Real>(zF.as_float()));
233 molecule->unitCell()->toCartesian(coord, coord);
234 atom.setPosition3d(coord);
235 } else {
236 error += "Missing y or z fractional coordinate on atom.";
237 return false;
238 }
239 }
240 }
241
242 // Check for 2D geometry.
243 {
244 /* XY2 Attribute Check */
245 xml_attribute x2Att = node.attribute("x2");
246 if (x2Att) {
247 xml_attribute y2 = node.attribute("y2");
248 if (y2) {
249 auto x = lexicalCast<double>(x2Att.value());
250 auto y = lexicalCast<double>(y2.value());
251 if (x && y) {
252 Vector2 position(*x, *y);
253 atom.setPosition2d(position);
254 } else {
255 error += "x2 or y2 attribute is malformed: ["s + x2Att.value() +
256 ", "s + y2.value() + "]."s;
257 return false;
258 }
259 } else {
260 // Corrupt 2D position supplied for atom.
261 return false;
262 }
263 }
264 }
265
266 // Check formal charge.
267 {
268 /* Formal Charge Attribute Check */
269 xml_attribute formalChargeAtt = node.attribute("formalCharge");
270 if (formalChargeAtt) {
271 if (auto formalCharge =
272 lexicalCast<signed int>(formalChargeAtt.value())) {
273 atom.setFormalCharge(*formalCharge);
274 } else {
275 error += "formalCharge attribute is malformed: "s +
276 formalChargeAtt.value();
277 return false;
278 }
279 }
280 }
281
282 // Move on to the next atom node (if there is one).
283 node = node.next_sibling("atom");
284 }
285 return true;
286 }
287
288 bool bonds()
289 {
290 xml_node bondArray = moleculeNode.child("bondArray");
291 if (!bondArray)
292 return true;
293
294 xml_node node = bondArray.child("bond");
295
296 while (node) {
297 xml_attribute attribute = node.attribute("atomRefs2");
298 Bond bond;
299 if (attribute) {
300 // Should contain two elements separated by a space.
301 std::string refs(attribute.value());
302 std::vector<std::string> tokens = split(refs, ' ');
303 if (tokens.size() != 2) // Corrupted file/input we don't understand
304 return false;
305 std::map<std::string, Index>::const_iterator begin, end;
306 begin = atomIds.find(tokens[0]);
307 end = atomIds.find(tokens[1]);
308 if (begin != atomIds.end() && end != atomIds.end() &&
309 begin->second < molecule->atomCount() &&
310 end->second < molecule->atomCount()) {
311 bond = molecule->addBond(molecule->atom(begin->second),
312 molecule->atom(end->second));
313 } else { // Couldn't parse the bond begin and end.
314 return false;
315 }
316 }
317
318 if (!bond.isValid()) {
319 // Couldn't create the bond.
320 return false;
321 }
322
323 attribute = node.attribute("order");
324 if (attribute && strlen(attribute.value()) == 1) {
325 char o = attribute.value()[0];
326 switch (o) {
327 case '1':
328 case 'S':
329 case 's':
330 bond.setOrder(1);
331 break;
332 case '2':
333 case 'D':
334 case 'd':
335 bond.setOrder(2);
336 break;
337 case '3':
338 case 'T':
339 case 't':
340 bond.setOrder(3);
341 break;
342 case '4':
343 bond.setOrder(4);
344 break;
345 case '5':
346 bond.setOrder(5);
347 break;
348 case '6':
349 bond.setOrder(6);
350 break;
351 default:
352 bond.setOrder(1);
353 }
354 } else {
355 bond.setOrder(1);
356 }
357
358 // Move on to the next bond node (if there is one).
359 node = node.next_sibling("bond");
360 }
361
362 return true;
363 }
364
365 #ifdef AVO_USE_HDF5
366 bool data()
367 {
368 xml_node dataNode = moleculeNode.child("dataMap").first_child();
369 if (!dataNode)
370 return true;
371
372 // Check if HDF5 file exists before attempting to open it
373 bool hdf5Available = false;
374 Hdf5DataFormat hdf5;
375 if (std::ifstream(filename + ".h5").good()) {
376 if (hdf5.openFile(filename + ".h5", Hdf5DataFormat::ReadOnly)) {
377 hdf5Available = true;
378 }
379 }
380 do {
381 std::string dataNodeName = dataNode.name();
382 std::string dataName = dataNode.attribute("name").as_string();
383 std::string dataType = dataNode.attribute("dataType").as_string();
384 std::stringstream dataStream(dataNode.text().as_string());
385 Variant variant;
386
387 // Read data from HDF5?
388 if (dataNodeName == "hdf5data") {
389 if (!hdf5Available) {
390 error += "CmlFormatPrivate::data: Cannot read data member '" +
391 dataName + "'. Cannot open file " + filename + ".h5.";
392 continue;
393 }
394
395 if (dataType != "xsd:double") {
396 error += "CmlFormatPrivate::data: Cannot read data member '" +
397 dataName + "'. Data type is not 'double'.";
398 continue;
399 }
400
401 MatrixX matrix;
402 if (!hdf5.readDataset(dataStream.str(), matrix)) {
403 error += "CmlFormatPrivate::data: Cannot read data member '" +
404 dataName + "': Unable to read data set '" +
405 dataStream.str() + "' from " + filename + ".h5";
406 continue;
407 }
408
409 variant.setValue(matrix);
410 }
411
412 // or read data from CML?
413 else if (dataNodeName == "scalar") {
414 if (dataType == "xsd:boolean") {
415 bool tmp;
416 dataStream >> tmp;
417 variant.setValue(tmp);
418 } else if (dataType == "xsd:int") {
419 int tmp;
420 dataStream >> tmp;
421 variant.setValue(tmp);
422 } else if (dataType == "xsd:long") {
423 long tmp;
424 dataStream >> tmp;
425 variant.setValue(tmp);
426 } else if (dataType == "xsd:float") {
427 float tmp;
428 dataStream >> tmp;
429 variant.setValue(tmp);
430 } else if (dataType == "xsd:double") {
431 double tmp;
432 dataStream >> tmp;
433 variant.setValue(tmp);
434 } else if (dataType == "xsd:string") {
435 string tmp;
436 dataStream >> tmp;
437 variant.setValue(tmp);
438 } else {
439 error +=
440 "CmlFormatPrivate::data: handled scalar data type: " + dataType;
441 continue;
442 }
443 }
444 molecule->setData(dataName, variant);
445 } while ((dataNode = dataNode.next_sibling()));
446
447 if (hdf5Available)
448 hdf5.closeFile();
449 return true;
450 }
451 #endif
452
453 bool success;
454 Molecule* molecule;
455 xml_node moleculeNode;
456 std::map<std::string, Index> atomIds;
457 string filename;
458 string error;
459 };
460 } // namespace
461
462 bool CmlFormat::read(std::istream& file, Core::Molecule& mol)
463 {
464 xml_document document;
465 pugi::xml_parse_result result = document.load(file);
466 if (!result) {
467 appendError("Error parsing XML: " + std::string(result.description()));
468 return false;
469 }
470
471 CmlFormatPrivate parser(&mol, document, fileName());
472 if (!parser.success)
473 appendError(parser.error);
474
475 return parser.success;
476 }
477
478 std::string formatNumber(std::stringstream& s, double n)
479 {
480 s.str(""); // clear it
481 s.precision(6);
482 s << n;
483 return s.str();
484 }
485
486 std::string formatNumber(std::stringstream& s, int n)
487 {
488 s.str(""); // clear it
489 s << n;
490 return s.str();
491 }
492
493 bool CmlFormat::write(std::ostream& out, const Core::Molecule& mol)
494 {
495 xml_document document;
496
497 // Imbue the output stream with the C numeric locale
498 // i.e. modify current stream locale with "C" numeric
499 std::locale currentLocale("");
500 std::locale numLocale(out.getloc(), "C", std::locale::numeric);
501 out.imbue(numLocale); // imbue modified locale
502
503 // We also need to set the locale temporarily for XML string formatting
504 std::stringstream
505 numberStream; // use this to format floats as C-format strings
506 numberStream.imbue(numLocale);
507
508 // Add a custom declaration node.
509 xml_node declaration = document.prepend_child(pugi::node_declaration);
510 declaration.append_attribute("version") = "1.0";
511 declaration.append_attribute("encoding") = "UTF-8";
512
513 xml_node moleculeNode = document.append_child("molecule");
514 // Standard XML namespaces for CML.
515 moleculeNode.append_attribute("xmlns") = "http://www.xml-cml.org/schema";
516 moleculeNode.append_attribute("xmlns:cml") =
517 "http://www.xml-cml.org/dictionary/cml";
518 moleculeNode.append_attribute("xmlns:units") =
519 "http://www.xml-cml.org/unit/nonSi";
520 moleculeNode.append_attribute("xmlns:xsd") =
521 "http://www.w3c.org/2001/XMLSchema";
522 moleculeNode.append_attribute("xmlns:iupac") = "http://www.iupac.org";
523
524 // Save the name if present into the file.
525 if (mol.data("name").type() == Variant::String) {
526 xml_node node = moleculeNode.append_child("name");
527 node.text() = mol.data("name").toString().c_str();
528 }
529
530 // If the InChI is available, embed that in the CML file.
531 if (mol.data("inchi").type() == Variant::String) {
532 xml_node node = moleculeNode.append_child("identifier");
533 node.append_attribute("convention") = "iupac:inchi";
534 node.append_attribute("value") = mol.data("inchi").toString().c_str();
535 }
536
537 // Cell specification
538 const UnitCell* cell = mol.unitCell();
539 if (cell) {
540 xml_node crystalNode = moleculeNode.append_child("crystal");
541
542 // Add the unit cell parameters.
543 xml_node crystalANode = crystalNode.append_child("scalar");
544 xml_node crystalBNode = crystalNode.append_child("scalar");
545 xml_node crystalCNode = crystalNode.append_child("scalar");
546 xml_node crystalAlphaNode = crystalNode.append_child("scalar");
547 xml_node crystalBetaNode = crystalNode.append_child("scalar");
548 xml_node crystalGammaNode = crystalNode.append_child("scalar");
549
550 crystalANode.append_attribute("title") = "a";
551 crystalBNode.append_attribute("title") = "b";
552 crystalCNode.append_attribute("title") = "c";
553 crystalAlphaNode.append_attribute("title") = "alpha";
554 crystalBetaNode.append_attribute("title") = "beta";
555 crystalGammaNode.append_attribute("title") = "gamma";
556
557 crystalANode.append_attribute("units") = "units:angstrom";
558 crystalBNode.append_attribute("units") = "units:angstrom";
559 crystalCNode.append_attribute("units") = "units:angstrom";
560 crystalAlphaNode.append_attribute("units") = "units:degree";
561 crystalBetaNode.append_attribute("units") = "units:degree";
562 crystalGammaNode.append_attribute("units") = "units:degree";
563
564 crystalANode.text() = formatNumber(numberStream, cell->a()).c_str();
565 crystalBNode.text() = formatNumber(numberStream, cell->b()).c_str();
566 crystalCNode.text() = formatNumber(numberStream, cell->c()).c_str();
567 crystalAlphaNode.text() =
568 formatNumber(numberStream, cell->alpha() * RAD_TO_DEG).c_str();
569 crystalBetaNode.text() =
570 formatNumber(numberStream, cell->beta() * RAD_TO_DEG).c_str();
571 crystalGammaNode.text() =
572 formatNumber(numberStream, cell->gamma() * RAD_TO_DEG).c_str();
573
574 // add the space group
575 unsigned short hall = mol.hallNumber();
576 if (hall != 0) {
577 xml_node spaceGroupNode = crystalNode.append_child("symmetry");
578 spaceGroupNode.append_attribute("spaceGroup") =
579 Core::SpaceGroups::international(hall);
580 }
581 }
582
583 xml_node atomArrayNode = moleculeNode.append_child("atomArray");
584 for (Index i = 0; i < mol.atomCount(); ++i) {
585 xml_node atomNode = atomArrayNode.append_child("atom");
586 std::ostringstream index;
587 index << 'a' << i + 1;
588 atomNode.append_attribute("id") = index.str().c_str();
589 Atom a = mol.atom(i);
590 atomNode.append_attribute("elementType") =
591 Elements::symbol(a.atomicNumber());
592 if (cell) {
593 Vector3 fracPos = cell->toFractional(a.position3d());
594 atomNode.append_attribute("xFract") =
595 formatNumber(numberStream, fracPos.x()).c_str();
596 atomNode.append_attribute("yFract") =
597 formatNumber(numberStream, fracPos.y()).c_str();
598 atomNode.append_attribute("zFract") =
599 formatNumber(numberStream, fracPos.z()).c_str();
600 } else {
601 atomNode.append_attribute("x3") =
602 formatNumber(numberStream, a.position3d().x()).c_str();
603 atomNode.append_attribute("y3") =
604 formatNumber(numberStream, a.position3d().y()).c_str();
605 atomNode.append_attribute("z3") =
606 formatNumber(numberStream, a.position3d().z()).c_str();
607 }
608 if (a.formalCharge() != 0) {
609 atomNode.append_attribute("formalCharge") =
610 formatNumber(numberStream, a.formalCharge()).c_str();
611 }
612 }
613
614 xml_node bondArrayNode = moleculeNode.append_child("bondArray");
615 for (Index i = 0; i < mol.bondCount(); ++i) {
616 xml_node bondNode = bondArrayNode.append_child("bond");
617 Bond b = mol.bond(i);
618 std::ostringstream index;
619 index << "a" << b.atom1().index() + 1 << " a" << b.atom2().index() + 1;
620 bondNode.append_attribute("atomRefs2") = index.str().c_str();
621 bondNode.append_attribute("order") = b.order();
622 }
623
624 #ifdef AVO_USE_HDF5
625 Hdf5DataFormat hdf5;
626 bool openFile = true;
627
628 xml_node dataMapNode = moleculeNode.append_child("dataMap");
629 VariantMap dataMap = mol.dataMap();
630 for (VariantMap::const_iterator it = dataMap.constBegin(),
631 itEnd = dataMap.constEnd();
632 it != itEnd; ++it) {
633 const std::string& name_ = (*it).first;
634
635 // Skip names that are handled elsewhere:
636 if (name_ == "inchi")
637 continue;
638
639 const Variant& var = (*it).second;
640 if (var.type() == Variant::Null) {
641 appendError("CmlFormat::writeFile: skipping null dataMap member '" +
642 name_ + "'.");
643 continue;
644 }
645
646 xml_node dataNode = dataMapNode.append_child();
647 dataNode.append_attribute("name") = name_.c_str();
648
649 switch (var.type()) {
650 case Variant::Null:
651 // Already skipped above
652 break;
653 case Variant::Bool:
654 dataNode.set_name("scalar");
655 dataNode.append_attribute("dataType") = "xsd:boolean";
656 dataNode.text() = var.toBool();
657 break;
658 case Variant::Int:
659 dataNode.set_name("scalar");
660 dataNode.append_attribute("dataType") = "xsd:int";
661 dataNode.text() = var.toInt();
662 break;
663 case Variant::Long:
664 dataNode.set_name("scalar");
665 dataNode.append_attribute("dataType") = "xsd:long";
666 dataNode.text() = var.toString().c_str();
667 break;
668 case Variant::Float:
669 dataNode.set_name("scalar");
670 dataNode.append_attribute("dataType") = "xsd:float";
671 dataNode.text() = var.toFloat();
672 break;
673 case Variant::Double:
674 dataNode.set_name("scalar");
675 dataNode.append_attribute("dataType") = "xsd:double";
676 dataNode.text() = var.toDouble();
677 break;
678 case Variant::Pointer:
679 appendError(
680 "CmlFormat::writeFile: Skipping void* molecule data member '" +
681 name_ + "'");
682 break;
683 case Variant::String:
684 dataNode.set_name("scalar");
685 dataNode.append_attribute("dataType") = "xsd:string";
686 dataNode.text() = var.toString().c_str();
687 break;
688 case Variant::Matrix: {
689 if (openFile) {
690 if (!hdf5.openFile(fileName() + ".h5",
691 Hdf5DataFormat::ReadWriteAppend)) {
692 appendError(
693 "CmlFormat::writeFile: Cannot open file: " + fileName() + ".h5");
694 }
695 openFile = false;
696 }
697
698 dataNode.set_name("hdf5data");
699 dataNode.append_attribute("dataType") = "xsd:double";
700 dataNode.append_attribute("ndims") = "2";
701 const MatrixX& matrix = var.toMatrixRef();
702 std::stringstream stream;
703 stream << matrix.rows() << " " << matrix.cols();
704 dataNode.append_attribute("dims") = stream.str().c_str();
705 std::string h5Path = "molecule/dataMap/"s + name_;
706 dataNode.text() = h5Path.c_str();
707 hdf5.writeDataset(h5Path, matrix);
708 } break;
709 default:
710 appendError("CmlFormat::writeFile: Unrecognized type for member '" +
711 name_ + "'.");
712 break;
713 }
714 }
715
716 hdf5.closeFile();
717 #endif
718
719 document.save(out, " ");
720
721 return true;
722 }
723
724 std::vector<std::string> CmlFormat::fileExtensions() const
725 {
726 std::vector<std::string> ext;
727 ext.emplace_back("cml");
728 return ext;
729 }
730
731 std::vector<std::string> CmlFormat::mimeTypes() const
732 {
733 std::vector<std::string> mime;
734 mime.emplace_back("chemical/x-cml");
735 return mime;
736 }
737
738 } // namespace Avogadro::Io