Debian Codegraph @

avogadro/io/mdlformat.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 "mdlformat.h"
7
8 #include "fileformatmanager.h"
9
10 #include <avogadro/core/elements.h>
11 #include <avogadro/core/molecule.h>
12 #include <avogadro/core/utilities.h>
13 #include <avogadro/core/vector.h>
14
15 #include <chrono>
16 #include <iomanip>
17 #include <iostream>
18 #include <istream>
19 #include <ostream>
20 #include <sstream>
21 #include <string>
22 #include <utility>
23
24 using Avogadro::Core::Array;
25 using Avogadro::Core::Atom;
26 using Avogadro::Core::Bond;
27 using Avogadro::Core::Elements;
28 using Avogadro::Core::endsWith;
29 using Avogadro::Core::lexicalCast;
30 using Avogadro::Core::split;
31 using Avogadro::Core::startsWith;
32 using Avogadro::Core::trimmed;
33
34 using std::getline;
35 using std::istringstream;
36 using std::setprecision;
37 using std::setw;
38 using std::string;
39
40 namespace Avogadro::Io {
41
42 using chargePair = std::pair<size_t, int>;
43 namespace {
44
45 // Helper function to handle partial charge property blocks
46 // e.g. PUBCHEM_MMFF94_PARTIAL_CHARGES
47 void handlePartialCharges(Core::Molecule& mol, std::string data,
48 std::string name = "MMFF94")
49 {
50 // the string starts with the number of charges
51 // then atom index charge
52 MatrixX charges(mol.atomCount(), 1);
53 std::istringstream iss(data);
54 size_t numCharges;
55 iss >> numCharges;
56 if (numCharges == 0 || numCharges > mol.atomCount()) {
57 return;
58 }
59
60 for (size_t i = 0; i < numCharges; ++i) {
61 if (!iss.good()) {
62 return;
63 }
64
65 size_t index = 0;
66 Real charge = 0.0;
67
68 iss >> index;
69 if (iss.fail() || index == 0 || index > mol.atomCount()) {
70 return;
71 }
72
73 iss >> charge;
74 if (iss.fail()) {
75 return;
76 }
77 // prints with atom index 1, not zero
78 charges(index - 1, 0) = charge;
79 }
80
81 // if present, remove atom.dpos and CHARGES from the string
82 if (startsWith(name, "atom.dpos")) {
83 name = name.substr(9, name.size() - 16);
84 }
85 if (endsWith(name, "CHARGES")) {
86 name = name.substr(0, name.size() - 7);
87 }
88
89 mol.setPartialCharges(name, charges);
90 }
91 } // namespace
92
93 bool MdlFormat::read(std::istream& in, Core::Molecule& mol)
94 {
95 string buffer;
96 int spinMultiplicity = 1; // check for RAD lines
97
98 // The first line is the molecule name.
99 getline(in, buffer);
100 buffer = trimmed(buffer);
101 // Check for the record separator in SDF, and skip if found.
102 if (buffer == "$$$$") {
103 getline(in, buffer);
104 buffer = trimmed(buffer);
105 }
106 if (!buffer.empty())
107 mol.setData("name", buffer);
108
109 if (!in.good()) {
110 appendError("Error reading molecule name.");
111 return false;
112 }
113
114 // check the generator line for 2D vs 3D
115 getline(in, buffer);
116 // e.g. -OEChem-01062507112D
117 // check the last 2 characters
118 if (buffer.size() >= 2 && buffer.compare(buffer.size() - 2, 2, "2D") == 0) {
119 m_is2D = true;
120
121 // we should use Open Babel and --gen3D
122 FileFormat* reader = nullptr;
123 std::vector<const FileFormat*> readers =
124 Io::FileFormatManager::instance().fileFormatsFromFileExtension(
125 "sdf", FileFormat::File | FileFormat::Read);
126
127 // loop through writers to check for "cclib" or "Open Babel"
128 for (const FileFormat* r : readers) {
129 if (r->identifier().compare(0, 9, "OpenBabel") == 0) {
130 reader = r->newInstance();
131 break;
132 }
133 }
134
135 // make sure to generate 3D coordinates
136 std::string options("{ \"arguments\": [\"--gen3D\"] }");
137 auto currentPos = in.tellg();
138 if (reader) {
139 reader->setOptions(options);
140 in.clear();
141 in.seekg(0);
142 if (reader->read(in, mol)) {
143 delete reader;
144 return true;
145 } else {
146 in.clear();
147 in.seekg(currentPos);
148 // continue with normal parsing
149 }
150 delete reader;
151 }
152 }
153
154 getline(in, buffer);
155 if (!in.good()) {
156 appendError("Error reading generator and comment lines.");
157 return false;
158 }
159
160 // The counts line, and version identifier.
161 getline(in, buffer);
162 // should be long enough, e.g.
163 // 5 4 0 0 0 0 0 0 0 0999 V2000
164 if (!in.good() || buffer.size() < 39) {
165 appendError("Error reading counts line.");
166 return false;
167 }
168
169 bool ok(false);
170 int numAtoms(lexicalCast<int>(buffer.substr(0, 3), ok));
171 if (!ok) {
172 appendError("Error parsing number of atoms.");
173 return false;
174 }
175 int numBonds(lexicalCast<int>(buffer.substr(3, 3), ok));
176 if (!ok) {
177 appendError("Error parsing number of bonds.");
178 return false;
179 }
180 string mdlVersion(trimmed(buffer.substr(33)));
181 if (mdlVersion == "V3000")
182 return readV3000(in, mol);
183 else if (mdlVersion != "V2000") {
184 appendError("Unsupported MDL version: " + mdlVersion);
185 return false;
186 }
187
188 // Parse the atom block.
189 std::vector<chargePair> chargeList;
190 std::vector<unsigned char> atomicNumbers; // Store for conformer validation
191 atomicNumbers.reserve(numAtoms);
192 for (int i = 0; i < numAtoms; ++i) {
193 Vector3 pos;
194 getline(in, buffer);
195 // 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
196 if (!in.good() || buffer.size() < 40) {
197 appendError("Error reading atom block.");
198 return false;
199 }
200
201 pos.x() = lexicalCast<Real>(buffer.substr(0, 10), ok);
202 if (!ok) {
203 appendError("Failed to parse x coordinate: " + buffer.substr(0, 10));
204 return false;
205 }
206 pos.y() = lexicalCast<Real>(buffer.substr(10, 10), ok);
207 if (!ok) {
208 appendError("Failed to parse y coordinate: " + buffer.substr(10, 10));
209 return false;
210 }
211 pos.z() = lexicalCast<Real>(buffer.substr(20, 10), ok);
212 if (!ok) {
213 appendError("Failed to parse z coordinate: " + buffer.substr(20, 10));
214 return false;
215 }
216
217 string element(trimmed(buffer.substr(31, 3)));
218 auto charge(lexicalCast<int>(trimmed(buffer.substr(36, 3))).value_or(0));
219 if (!buffer.empty()) {
220 unsigned char atomicNum = Elements::atomicNumberFromSymbol(element);
221 if (element == "D" || element == "T")
222 atomicNum = 1; // Deuterium and Tritium are hydrogen
223 atomicNumbers.push_back(atomicNum);
224 Atom newAtom = mol.addAtom(atomicNum);
225 if (element == "D") {
226 newAtom.setIsotope(2);
227 } else if (element == "T") {
228 newAtom.setIsotope(3);
229 }
230
231 newAtom.setPosition3d(pos);
232 // In case there's no CHG property
233 if (charge == 4) // doublet radical
234 spinMultiplicity += 1;
235
236 charge = (charge > 4) ? ((charge <= 7) ? 4 - charge : 0)
237 : ((charge < 4) ? charge : 0);
238 if (charge)
239 chargeList.emplace_back(newAtom.index(), charge);
240
241 // vvv field: valence (columns 48-50), 0 = default
242 if (buffer.size() >= 51) {
243 int valence =
244 lexicalCast<int>(trimmed(buffer.substr(48, 3))).value_or(0);
245 if (valence > 0 && valence <= 6) {
246 Core::AtomHybridization hyb = Core::HybridizationUnknown;
247 if (valence <= 2)
248 hyb = Core::SP;
249 else if (valence == 3)
250 hyb = Core::SP2;
251 else if (valence == 4)
252 hyb = Core::SP3;
253 else if (valence == 5)
254 hyb = Core::TrigonalBipyramidal;
255 else if (valence == 6)
256 hyb = Core::Octahedral;
257 mol.setHybridization(newAtom.index(), hyb);
258 }
259 }
260 continue;
261 } else {
262 appendError("Error parsing atom block: " + buffer);
263 return false;
264 }
265 }
266
267 // Parse the bond block.
268 for (int i = 0; i < numBonds; ++i) {
269 // Bond atom indices start at 1, -1 for C++.
270 getline(in, buffer);
271 // 1 2 1 0 0 0 0
272 if (!in.good() || buffer.size() < 10) {
273 appendError("Error reading bond block.");
274 return false;
275 }
276
277 int begin(lexicalCast<int>(buffer.substr(0, 3), ok) - 1);
278 if (!ok) {
279 appendError("Error parsing beginning bond index:" + buffer.substr(0, 3));
280 return false;
281 }
282 int end(lexicalCast<int>(buffer.substr(3, 3), ok) - 1);
283 if (!ok) {
284 appendError("Error parsing end bond index:" + buffer.substr(3, 3));
285 return false;
286 }
287 int order(lexicalCast<int>(buffer.substr(6, 3), ok));
288 if (!ok) {
289 appendError("Error parsing bond order:" + buffer.substr(6, 3));
290 return false;
291 }
292 if (begin < 0 || begin >= numAtoms || end < 0 || end >= numAtoms) {
293 appendError("Bond read in with out of bounds index.");
294 return false;
295 }
296 mol.addBond(mol.atom(begin), mol.atom(end),
297 static_cast<unsigned char>(order));
298 }
299
300 // Parse the properties block until the end of the file.
301 // Property lines count is not used, as it it now unsupported.
302 bool foundEnd(false);
303 bool foundChgProperty(false);
304 while (getline(in, buffer)) {
305 if (!in.good() || buffer.size() < 5) {
306 break;
307 }
308
309 if (startsWith(buffer, "M END") || startsWith(buffer, "M END")) {
310 foundEnd = true;
311 break;
312 } else if (buffer.size() >= 6 && buffer.substr(0, 6) == "M CHG") {
313 if (!foundChgProperty)
314 chargeList.clear(); // Forget old-style charges
315 size_t entryCount(lexicalCast<int>(buffer.substr(6, 3), ok));
316 if (buffer.length() < 17 + 8 * (entryCount - 1)) {
317 appendError("Error parsing charge block.");
318 std::cout << " " << entryCount << " " << buffer.length() << std::endl;
319 return false;
320 }
321
322 for (size_t i = 0; i < entryCount; i++) {
323 size_t index(lexicalCast<size_t>(buffer.substr(10 + 8 * i, 3), ok) - 1);
324 if (!ok) {
325 appendError("Error parsing charged atom index:" +
326 buffer.substr(10 + 8 * i, 3));
327 return false;
328 }
329 auto charge(lexicalCast<int>(buffer.substr(14 + 8 * i, 3), ok));
330 if (!ok) {
331 appendError("Error parsing atom charge:" +
332 buffer.substr(14 + 8 * i, 3));
333 return false;
334 }
335 if (charge)
336 chargeList.emplace_back(index, charge);
337 }
338 } else if (buffer.size() >= 6 && buffer.substr(0, 6) == "M RAD") {
339 // radical center
340 spinMultiplicity = 1; // reset and count
341 size_t entryCount(lexicalCast<int>(buffer.substr(6, 3), ok));
342 if (buffer.length() < 17 + 8 * (entryCount - 1)) {
343 appendError("Error parsing radical block.");
344 return false;
345 }
346
347 for (size_t i = 0; i < entryCount; i++) {
348 [[maybe_unused]] size_t index(
349 lexicalCast<size_t>(buffer.substr(10 + 8 * i, 3), ok) - 1);
350 if (!ok) {
351 appendError("Error parsing radical atom index:" +
352 buffer.substr(10 + 8 * i, 3));
353 return false;
354 }
355 auto radical(lexicalCast<int>(buffer.substr(14 + 8 * i, 3), ok));
356 if (!ok) {
357 appendError("Error parsing radical type:" +
358 buffer.substr(14 + 8 * i, 3));
359 return false;
360 }
361 // we don't set radical centers, just count them
362 // for the total spin multiplicity
363 if (radical == 2) // doublet
364 spinMultiplicity += 1;
365 else if (radical == 3) // triplet
366 spinMultiplicity += 2;
367 }
368 } else if (buffer.size() >= 6 && buffer.substr(0, 6) == "M ISO") {
369 // isotope
370 size_t entryCount(lexicalCast<int>(buffer.substr(6, 3), ok));
371 if (buffer.length() < 17 + 8 * (entryCount - 1)) {
372 appendError("Error parsing isotope block.");
373 return false;
374 }
375
376 for (size_t i = 0; i < entryCount; i++) {
377 size_t index(lexicalCast<size_t>(buffer.substr(10 + 8 * i, 3), ok) - 1);
378 if (!ok) {
379 appendError("Error parsing isotope atom index:" +
380 buffer.substr(10 + 8 * i, 3));
381 return false;
382 }
383 auto isotope(lexicalCast<int>(buffer.substr(14 + 8 * i, 3), ok));
384 if (!ok) {
385 appendError("Error parsing isotope type:" +
386 buffer.substr(14 + 8 * i, 3));
387 return false;
388 }
389 mol.setIsotope(index, isotope);
390 }
391 } // isotope
392 #ifndef NDEBUG
393 else if (buffer.size() >= 6) {
394 std::cout << " prefix " << buffer.substr(0, 6) << std::endl;
395 }
396 #endif
397 }
398
399 if (!foundEnd) {
400 appendError("Error, ending tag for file not found.");
401 // return false;
402 }
403
404 // Apply charges.
405 for (auto& i : chargeList) {
406 size_t index = i.first;
407 signed int charge = i.second;
408 mol.setFormalCharge(index, charge);
409 }
410
411 // Set the total spin multiplicity
412 if (spinMultiplicity > 1)
413 mol.setData("totalSpinMultiplicity", spinMultiplicity);
414
415 // Check that all atoms were handled.
416 if (mol.atomCount() != static_cast<size_t>(numAtoms) ||
417 mol.bondCount() != static_cast<size_t>(numBonds)) {
418 std::ostringstream errorStream;
419 errorStream << "Error parsing file, got " << mol.atomCount()
420 << "atoms, expected " << numAtoms << ", got " << mol.bondCount()
421 << ", expected " << numBonds << ".";
422 appendError(errorStream.str());
423 return false;
424 }
425
426 // Now parse the data block.
427 bool inValue(false);
428 string dataName;
429 string dataValue;
430 while (getline(in, buffer) && in.good()) {
431 if (trimmed(buffer) == "$$$$")
432 break;
433 if (inValue) {
434 // Use trimmed() to handle Windows CRLF line endings where \r remains
435 if (trimmed(buffer).empty() && dataName.length() > 0) {
436 // check for partial charges
437 if (dataName == "PUBCHEM_MMFF94_PARTIAL_CHARGES")
438 handlePartialCharges(mol, dataValue);
439 else if (startsWith(dataName, "atom.dpos") &&
440 endsWith(dataName, "CHARGES"))
441 // remove the "CHARGES" from the end of the string
442 handlePartialCharges(mol, dataValue, dataName);
443 else
444 mol.setData(dataName, dataValue);
445
446 dataName.clear();
447 dataValue.clear();
448 inValue = false;
449 } else {
450 if (dataValue.length())
451 dataValue += "\n";
452 dataValue += trimmed(buffer);
453 }
454 } else if (startsWith(buffer, "> ")) {
455 // This is a data header, read the name of the entry, and the value on
456 // the following lines.
457 // e.g., > <propName>
458 // dataName will be anything from < to >
459 size_t start = buffer.find('<');
460 size_t end = buffer.find('>', start);
461 if (start != string::npos && end != string::npos) {
462 dataName = buffer.substr(start + 1, end - start - 1);
463 inValue = true;
464 }
465 }
466 }
467
468 // handle pKa from QupKake model
469 if (mol.hasData("pka") && mol.hasData("idx")) {
470 // pka can sometimes say "tensor(3.1452)" or "3.1452"
471 // just convert to a string with 2 decimal places
472 std::string pka = mol.data("pka").toString();
473 if (startsWith(pka, "tensor("))
474 pka = pka.substr(7, pka.size() - 8);
475 // find the decimal to only keep 2 decimal places
476 size_t decimal = pka.find(".");
477 if (decimal != std::string::npos)
478 pka = pka.substr(0, decimal + 3);
479 mol.setData("pka", pka);
480 // convert the idx to an atom index
481 // and set the label
482 std::string idx = mol.data("idx").toString();
483 size_t atomIdx = lexicalCast<size_t>(idx).value_or(0);
484 mol.setAtomLabel(atomIdx, pka);
485 }
486
487 // Read additional conformers from the file
488 // Save the initial coordinates as coordinate set 0
489 mol.setCoordinate3d(mol.atomPositions3d(), 0);
490 int coordSet = 1;
491
492 // Look for additional molecule blocks after $$$$
493 // (in case there are multiple conformers / coordinates)
494 // e.g. this is a multi-conformer or trajectory file
495 while (in.good()) {
496 // Save position at start of potential molecule block
497 std::streampos molPos = in.tellg();
498
499 // Skip to start of next molecule (should already be at $$$$ or past it)
500 // Read the molecule name line
501 if (!getline(in, buffer))
502 break;
503 buffer = trimmed(buffer);
504
505 // Skip $$$$ if we encounter it
506 if (buffer == "$$$$") {
507 // Update position to after $$$$, at start of next molecule
508 molPos = in.tellg();
509 if (!getline(in, buffer))
510 break;
511 buffer = trimmed(buffer);
512 }
513
514 // Empty line or EOF means no more molecules
515 if (buffer.empty() && !in.good())
516 break;
517
518 // Skip generator and comment lines
519 if (!getline(in, buffer) || !getline(in, buffer))
520 break;
521
522 // Read counts line
523 if (!getline(in, buffer) || buffer.size() < 39)
524 break;
525
526 // Check if this is V3000 - skip if so
527 // (that would be weird mixing V2000 and V3000)
528 string version(trimmed(buffer.substr(33)));
529 if (version == "V3000") {
530 // Restore stream position for potential future reading
531 if (molPos != std::streampos(-1))
532 in.seekg(molPos);
533 break;
534 }
535
536 // Parse atom count and verify it matches
537 int confAtoms = lexicalCast<int>(buffer.substr(0, 3), ok);
538 if (!ok || confAtoms != numAtoms) {
539 // Different molecule - restore stream position
540 if (molPos != std::streampos(-1))
541 in.seekg(molPos);
542 break;
543 }
544
545 int confBonds = lexicalCast<int>(buffer.substr(3, 3), ok);
546 if (!ok)
547 break;
548
549 // Parse atom block and collect positions
550 Array<Vector3> positions;
551 positions.reserve(numAtoms);
552 bool validConformer = true;
553
554 for (int i = 0; i < confAtoms; ++i) {
555 if (!getline(in, buffer) || buffer.size() < 40) {
556 validConformer = false;
557 break;
558 }
559
560 Vector3 pos;
561 pos.x() = lexicalCast<Real>(buffer.substr(0, 10), ok);
562 if (!ok) {
563 validConformer = false;
564 break;
565 }
566 pos.y() = lexicalCast<Real>(buffer.substr(10, 10), ok);
567 if (!ok) {
568 validConformer = false;
569 break;
570 }
571 pos.z() = lexicalCast<Real>(buffer.substr(20, 10), ok);
572 if (!ok) {
573 validConformer = false;
574 break;
575 }
576
577 // Check element matches
578 string element(trimmed(buffer.substr(31, 3)));
579 unsigned char atomicNum = Elements::atomicNumberFromSymbol(element);
580 if (element == "D" || element == "T")
581 atomicNum = 1;
582
583 if (atomicNum != atomicNumbers[i]) {
584 validConformer = false;
585 break; // Different element, not the same molecule
586 }
587
588 positions.push_back(pos);
589 }
590
591 if (!validConformer) {
592 // Different molecule or parse error - restore stream position
593 if (molPos != std::streampos(-1))
594 in.seekg(molPos);
595 break;
596 }
597
598 // Skip bond block
599 for (int i = 0; i < confBonds; ++i) {
600 if (!getline(in, buffer))
601 break;
602 }
603
604 // Skip properties block until M END
605 // TODO: Consider reading properties in the future
606 // (e.g. if radicals or charges change during a trajectory)
607 while (getline(in, buffer)) {
608 if (startsWith(buffer, "M END") || startsWith(buffer, "M END"))
609 break;
610 }
611
612 // Skip data block until $$$$
613 // TODO: Consider reading data from conformers in the future
614 // e.g. energies, etc.
615 while (getline(in, buffer)) {
616 if (trimmed(buffer) == "$$$$")
617 break;
618 }
619
620 // Add the conformer coordinates
621 mol.setCoordinate3d(positions, coordSet++);
622 }
623
624 return true;
625 }
626
627 bool MdlFormat::readV3000(std::istream& in, Core::Molecule& mol)
628 {
629 string buffer;
630 int spinMultiplicity = 1; // check for RAD lines
631 // we should have M V30 BEGIN CTAB
632 getline(in, buffer);
633 if (trimmed(buffer) != "M V30 BEGIN CTAB") {
634 appendError("Error parsing V3000 file, expected 'M V30 BEGIN CTAB'.");
635 return false;
636 }
637 // now we should get the counts line
638 // e.g. 'M V30 COUNTS 23694 24297 0 0 1'
639 getline(in, buffer);
640 // split by whitespace
641 std::vector<string> counts = split(trimmed(buffer), ' ');
642 if (counts.size() < 5) {
643 appendError("Error parsing V3000 counts line.");
644 return false;
645 }
646 bool ok(false);
647 int numAtoms(lexicalCast<int>(counts[3], ok));
648 if (!ok) {
649 appendError("Error parsing number of atoms.");
650 return false;
651 }
652 int numBonds(lexicalCast<int>(counts[4], ok));
653 if (!ok) {
654 appendError("Error parsing number of bonds.");
655 return false;
656 }
657
658 // Parse the atom block.
659 // 'M V30 BEGIN ATOM'
660 // 'M V30 1 N 171.646 251.874 224.877 0'
661 getline(in, buffer);
662 if (trimmed(buffer) != "M V30 BEGIN ATOM") {
663 appendError("Error parsing V3000 atom block.");
664 return false;
665 }
666 for (int i = 0; i < numAtoms; ++i) {
667 getline(in, buffer);
668 std::vector<string> atomData = split(trimmed(buffer), ' ');
669 if (atomData.size() < 7) {
670 appendError("Error parsing V3000 atom line.");
671 return false;
672 }
673
674 string element(trimmed(atomData[3]));
675 unsigned char atomicNum = Elements::atomicNumberFromSymbol(element);
676 Atom newAtom = mol.addAtom(atomicNum);
677 if (element == "D") {
678 newAtom.setAtomicNumber(1);
679 newAtom.setIsotope(2);
680 } else if (element == "T") {
681 newAtom.setAtomicNumber(1);
682 newAtom.setIsotope(3);
683 }
684
685 Vector3 pos;
686 pos.x() = lexicalCast<Real>(atomData[4], ok);
687 if (!ok) {
688 appendError("Failed to parse x coordinate: " + atomData[3]);
689 return false;
690 }
691 pos.y() = lexicalCast<Real>(atomData[5], ok);
692 if (!ok) {
693 appendError("Failed to parse y coordinate: " + atomData[4]);
694 return false;
695 }
696 pos.z() = lexicalCast<Real>(atomData[6], ok);
697 if (!ok) {
698 appendError("Failed to parse z coordinate: " + atomData[5]);
699 return false;
700 }
701 newAtom.setPosition3d(pos);
702 // check for formal charge in the atom block
703 // CHG=1 for example
704 if (atomData.size() > 8) {
705 // loop through the key=value pairs
706 for (size_t j = 8; j < atomData.size(); ++j) {
707 string key = atomData[j];
708 if (startsWith(key, "CHG=")) {
709 int charge = lexicalCast<int>(key.substr(4), ok);
710 if (!ok) {
711 appendError("Failed to parse atom charge: " + key);
712 return false;
713 }
714 newAtom.setFormalCharge(charge);
715 } else if (startsWith(key, "RAD=")) {
716 // radical center
717 int radical = lexicalCast<int>(key.substr(4), ok);
718 if (!ok) {
719 appendError("Failed to parse radical type: " + key);
720 return false;
721 }
722 // we don't set radical centers, just count them
723 // for the total spin multiplicity
724 if (radical == 2) // doublet
725 spinMultiplicity += 1;
726 else if (radical == 3) // triplet
727 spinMultiplicity += 2;
728 } else if (startsWith(key, "ISO=")) {
729 // isotope
730 int isotope = lexicalCast<int>(key.substr(4), ok);
731 if (!ok) {
732 appendError("Failed to parse isotope type: " + key);
733 return false;
734 }
735 mol.setIsotope(newAtom.index(), isotope);
736 } else if (startsWith(key, "VAL=")) {
737 // explicit valence — map to hybridization
738 int valence = lexicalCast<int>(key.substr(4), ok);
739 if (!ok) {
740 appendError("Failed to parse valence: " + key);
741 return false;
742 }
743 // VAL=0 means "no marking" (default), VAL=-1 means zero valence
744 if (valence > 0 && valence <= 6) {
745 Core::AtomHybridization hyb = Core::HybridizationUnknown;
746 if (valence <= 2)
747 hyb = Core::SP;
748 else if (valence == 3)
749 hyb = Core::SP2;
750 else if (valence == 4)
751 hyb = Core::SP3;
752 else if (valence == 5)
753 hyb = Core::TrigonalBipyramidal;
754 else if (valence == 6)
755 hyb = Core::Octahedral;
756 mol.setHybridization(newAtom.index(), hyb);
757 }
758 } else {
759 #ifndef NDEBUG
760 std::cerr << "Unknown key: " << key << std::endl;
761 #endif
762 }
763 } // end of key-value loop
764 }
765 } // end of atom block
766 getline(in, buffer);
767 // check for END ATOM
768 if (trimmed(buffer) != "M V30 END ATOM") {
769 appendError("Error parsing V3000 atom block.");
770 return false;
771 }
772
773 // bond block
774 // 'M V30 BEGIN BOND'
775 // 'M V30 1 1 1 2'
776 getline(in, buffer);
777 if (trimmed(buffer) != "M V30 BEGIN BOND") {
778 appendError("Error parsing V3000 bond block.");
779 return false;
780 }
781 for (int i = 0; i < numBonds; ++i) {
782 getline(in, buffer);
783 std::vector<string> bondData = split(trimmed(buffer), ' ');
784 if (bondData.size() < 5) {
785 appendError("Error parsing V3000 bond line.");
786 return false;
787 }
788 int order = lexicalCast<int>(bondData[3], ok);
789 if (!ok) {
790 appendError("Failed to parse bond order: " + bondData[3]);
791 return false;
792 }
793 int atom1 = lexicalCast<int>(bondData[4], ok) - 1;
794 if (!ok) {
795 appendError("Failed to parse bond atom1: " + bondData[4]);
796 return false;
797 }
798 int atom2 = lexicalCast<int>(bondData[5], ok) - 1;
799 if (!ok) {
800 appendError("Failed to parse bond atom2: " + bondData[5]);
801 return false;
802 }
803 mol.addBond(mol.atom(atom1), mol.atom(atom2),
804 static_cast<unsigned char>(order));
805 } // end of bond block
806
807 // look for M END
808 while (getline(in, buffer)) {
809 if (trimmed(buffer) == "M END")
810 break;
811 }
812 // read in any properties
813 while (getline(in, buffer)) {
814 if (startsWith(buffer, "> <")) {
815 string key = trimmed(buffer.substr(3, buffer.length() - 4));
816 string value;
817 while (getline(in, buffer)) {
818 if (trimmed(buffer) == "")
819 break;
820 value += buffer + "\n";
821 }
822 mol.setData(key, value);
823 }
824 }
825
826 // if we have a spin multiplicity, set it
827 if (spinMultiplicity > 1)
828 mol.setData("totalSpinMultiplicity", spinMultiplicity);
829
830 return true;
831 }
832
833 bool MdlFormat::writeV3000(std::ostream& out, const Core::Molecule& mol)
834 {
835 // write the "fake" counts line
836 out << " 0 0 0 0 0 999 V3000\n";
837 out << "M V30 BEGIN CTAB\n";
838 out << "M V30 COUNTS " << mol.atomCount() << ' ' << mol.bondCount()
839 << " 0 0 0\n";
840 // atom block
841 out << "M V30 BEGIN ATOM\n";
842 for (size_t i = 0; i < mol.atomCount(); ++i) {
843 Atom atom = mol.atom(i);
844 out << "M V30 " << i + 1 << ' ' << Elements::symbol(atom.atomicNumber())
845 << ' ' << atom.position3d().x() << ' ' << atom.position3d().y() << ' '
846 << atom.position3d().z() << " 0";
847 if (atom.formalCharge())
848 out << " CHG=" << atom.formalCharge();
849 out << "\n";
850 }
851 out << "M V30 END ATOM\n";
852 // bond block
853 out << "M V30 BEGIN BOND\n";
854 for (size_t i = 0; i < mol.bondCount(); ++i) {
855 Bond bond = mol.bond(i);
856 out << "M V30 " << i + 1 << ' ' << static_cast<int>(bond.order()) << ' '
857 << (bond.atom1().index() + 1) << ' ' << (bond.atom2().index() + 1)
858 << " \n";
859 }
860 out << "M V30 END BOND\n";
861 out << "M V30 END CTAB\n";
862 out << "M END\n";
863
864 // TODO: isotopes, radicals, etc.
865 if (m_writeProperties) {
866 const auto dataMap = mol.dataMap();
867 for (const auto& key : dataMap.names()) {
868 // skip some keys
869 if (key == "modelView" || key == "projection")
870 continue;
871
872 out << "> <" << key << ">\n";
873 out << dataMap.value(key).toString() << "\n";
874 out << "\n"; // empty line between data blocks
875 }
876 }
877
878 if (m_writeProperties || isMode(FileFormat::MultiMolecule))
879 out << "$$$$\n";
880
881 return true;
882 }
883
884 bool MdlFormat::write(std::ostream& out, const Core::Molecule& mol)
885 {
886 // Header lines.
887 out << mol.data("name").toString() << "\n";
888
889 // Mol block header - need to indicate 3D coords
890 // e.g. Avogadro08072512293D
891 // name of program MMDDYYHM3D
892 auto now = std::chrono::system_clock::now();
893 // Convert to time_t for use with ctime functions
894 std::time_t time_t_now = std::chrono::system_clock::to_time_t(now);
895 // Convert to a local time structure (tm)
896 std::tm* local_time = std::localtime(&time_t_now);
897
898 // Format the time using std::put_time
899 // %m: Month as decimal number (01-12)
900 // %d: Day of the month as decimal number (01-31)
901 // %y: Year without century (00-99)
902 // %H: Hour in 24-hour format (00-23)
903 // %M: Minute as decimal number (00-59)
904 out << " Avogadro" << std::put_time(local_time, "%m%d%y%H%M") << "3D\n\n";
905
906 // Counts line.
907 if (mol.atomCount() > 999 || mol.bondCount() > 999) {
908 // we need V3000 support for big molecules
909 return writeV3000(out, mol);
910 }
911
912 out << setw(3) << std::right << mol.atomCount() << setw(3) << mol.bondCount()
913 << " 0 0 0 0 0 0 0 0999 V2000\n";
914 // Atom block.
915 std::vector<chargePair> chargeList;
916 for (size_t i = 0; i < mol.atomCount(); ++i) {
917 Atom atom = mol.atom(i);
918 signed int charge = atom.formalCharge();
919 if (charge)
920 chargeList.emplace_back(atom.index(), charge);
921 unsigned int chargeField = (charge < 0) ? ((charge >= -3) ? 4 - charge : 0)
922 : ((charge <= 3) ? charge : 0);
923 out << setw(10) << std::right << std::fixed << setprecision(4)
924 << atom.position3d().x() << setw(10) << atom.position3d().y()
925 << setw(10) << atom.position3d().z() << ' ' << setw(3) << std::left
926 << Elements::symbol(atom.atomicNumber()) << " 0" << setw(3)
927 << std::right << chargeField /* for compatibility */
928 << " 0 0 0 0 0 0 0 0 0 0\n";
929 }
930 // Bond block.
931 for (size_t i = 0; i < mol.bondCount(); ++i) {
932 Bond bond = mol.bond(i);
933 out.unsetf(std::ios::floatfield);
934 out << setw(3) << std::right << bond.atom1().index() + 1 << setw(3)
935 << bond.atom2().index() + 1 << setw(3) << static_cast<int>(bond.order())
936 << " 0 0 0 0\n";
937 }
938 // Properties block.
939 for (auto& i : chargeList) {
940 Index atomIndex = i.first;
941 signed int atomCharge = i.second;
942 out << "M CHG 1 " << setw(3) << std::right << atomIndex + 1 << ' '
943 << setw(3) << atomCharge << "\n";
944 }
945 // TODO: isotopes, etc.
946 out << "M END\n";
947 // Data block
948 if (m_writeProperties) {
949 const auto dataMap = mol.dataMap();
950 for (const auto& key : dataMap.names()) {
951 // skip some keys
952 if (key == "modelView" || key == "projection")
953 continue;
954
955 out << "> <" << key << ">\n";
956 out << dataMap.value(key).toString() << "\n";
957 out << "\n"; // empty line between data blocks
958 }
959 }
960
961 if (m_writeProperties || isMode(FileFormat::MultiMolecule))
962 out << "$$$$\n";
963
964 return true;
965 }
966
967 std::vector<std::string> MdlFormat::fileExtensions() const
968 {
969 std::vector<std::string> ext;
970 ext.emplace_back("mol");
971 return ext;
972 }
973
974 std::vector<std::string> MdlFormat::mimeTypes() const
975 {
976 std::vector<std::string> mime;
977 mime.emplace_back("chemical/x-mdl-molfile");
978 return mime;
979 }
980
981 } // namespace Avogadro::Io