Debian Codegraph @

avogadro/io/cjsonformat.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 "cjsonformat.h"
7
8 #include <avogadro/core/crystaltools.h>
9 #include <avogadro/core/cube.h>
10 #include <avogadro/core/elements.h>
11 #include <avogadro/core/gaussianset.h>
12 #include <avogadro/core/layermanager.h>
13 #include <avogadro/core/molecule.h>
14 #include <avogadro/core/residue.h>
15 #include <avogadro/core/spacegroups.h>
16 #include <avogadro/core/unitcell.h>
17 #include <avogadro/core/utilities.h>
18
19 #include <nlohmann/json.hpp>
20
21 #include <cstdio>
22 #include <iomanip>
23 #include <iostream>
24 #include <iterator>
25
26 using json = nlohmann::json;
27 using ordered_json = nlohmann::ordered_json;
28
29 namespace Avogadro::Io {
30
31 using std::string;
32 using std::vector;
33
34 using Core::Array;
35 using Core::Atom;
36 using Core::BasisSet;
37 using Core::Bond;
38 using Core::CrystalTools;
39 using Core::Cube;
40 using Core::GaussianSet;
41 using Core::LayerData;
42 using Core::LayerManager;
43 using Core::Molecule;
44 using Core::Residue;
45 using Core::Variant;
46
47 bool setJsonKey(json& j, Molecule& m, const std::string& key)
48 {
49 if (j.count(key) && j.find(key)->is_string()) {
50 m.setData(key, j.value(key, "undefined"));
51 return true;
52 }
53 return false;
54 }
55
56 bool isNumericArray(json& j)
57 {
58 if (j.is_array() && j.size() > 0) {
59 for (const auto& v : j) {
60 if (!v.is_number()) {
61 return false;
62 }
63 }
64 return true;
65 }
66 return false;
67 }
68
69 bool isBooleanArray(json& j)
70 {
71 if (j.is_array() && j.size() > 0) {
72 for (const auto& v : j) {
73 if (!v.is_boolean()) {
74 return false;
75 }
76 }
77 return true;
78 }
79 return false;
80 }
81
82 json eigenColToJson(const MatrixX& matrix, int column)
83 {
84 json j;
85 j = json::array();
86 for (Eigen::Index i = 0; i < matrix.rows(); ++i) {
87 j.push_back(matrix(i, column));
88 }
89 return j;
90 }
91
92 // Sanitize a raw string by replacing invalid UTF-8 sequences with '?'
93 // (to work around a bug in Open Babel space group output)
94 std::string sanitizeUtf8(const std::string& s)
95 {
96 std::string result;
97 result.reserve(s.size());
98 const unsigned char* bytes = reinterpret_cast<const unsigned char*>(s.data());
99 size_t len = s.size();
100
101 for (size_t i = 0; i < len; ++i) {
102 if (bytes[i] <= 0x7F) {
103 result.push_back(static_cast<char>(bytes[i]));
104 continue;
105 }
106
107 size_t remaining = 0;
108 if ((bytes[i] & 0xE0) == 0xC0)
109 remaining = 1;
110 else if ((bytes[i] & 0xF0) == 0xE0)
111 remaining = 2;
112 else if ((bytes[i] & 0xF8) == 0xF0)
113 remaining = 3;
114 else {
115 result.push_back('?'); // invalid lead byte
116 continue;
117 }
118
119 if (i + remaining >= len) {
120 result.push_back('?'); // truncated sequence
121 continue;
122 }
123
124 bool valid = true;
125 for (size_t j = 1; j <= remaining; ++j) {
126 if ((bytes[i + j] & 0xC0) != 0x80) {
127 valid = false;
128 break;
129 }
130 }
131
132 if (valid) {
133 for (size_t j = 0; j <= remaining; ++j)
134 result.push_back(static_cast<char>(bytes[i + j]));
135 i += remaining;
136 } else {
137 result.push_back('?'); // invalid continuation
138 }
139 }
140 return result;
141 }
142
143 bool CjsonFormat::read(std::istream& file, Molecule& molecule)
144 {
145 return deserialize(file, molecule, true);
146 }
147
148 bool CjsonFormat::deserialize(std::istream& file, Molecule& molecule,
149 bool isJson)
150 {
151 json jsonRoot;
152
153 // could throw parse errors
154 try {
155 if (isJson)
156 jsonRoot = json::parse(file, nullptr, false);
157 else // msgpack
158 jsonRoot = json::from_msgpack(file);
159 } catch (json::parse_error& e) {
160 appendError("Error reading CJSON file: " + string(e.what()));
161 return false;
162 } catch (json::type_error& e) {
163 appendError("Error reading CJSON file: " + string(e.what()));
164 return false;
165 }
166
167 if (jsonRoot.is_discarded() && isJson) {
168 // Initial parse failed - try sanitizing UTF-8 and re-parsing
169 file.clear();
170 file.seekg(0);
171 std::string content((std::istreambuf_iterator<char>(file)),
172 std::istreambuf_iterator<char>());
173 std::string sanitizedContent = sanitizeUtf8(content);
174 jsonRoot = json::parse(sanitizedContent, nullptr, false);
175 }
176
177 if (jsonRoot.is_discarded()) {
178 appendError("Error reading CJSON file. Root is discarded.");
179 return false;
180 }
181
182 if (!jsonRoot.is_object()) {
183 appendError("Error: Input is not a JSON object.");
184 return false;
185 }
186
187 auto jsonValue = jsonRoot.find("chemicalJson");
188 if (jsonValue == jsonRoot.end())
189 jsonValue = jsonRoot.find("chemical json");
190 if (jsonValue == jsonRoot.end()) {
191 appendError("Error: no \"chemical json\" key found.");
192 return false;
193 }
194 if (*jsonValue != 0 && *jsonValue != 1) {
195 appendError("Warning: chemical json version is not 0 or 1.");
196 return false;
197 }
198
199 // Read some basic key-value pairs (all strings).
200 setJsonKey(jsonRoot, molecule, "name");
201 setJsonKey(jsonRoot, molecule, "inchi");
202 setJsonKey(jsonRoot, molecule, "formula");
203
204 // Read in the atoms.
205 json atoms = jsonRoot["atoms"];
206 if (!atoms.is_object()) {
207 appendError("The 'atoms' key does not contain an object.");
208 return false;
209 }
210
211 if (!atoms.contains("elements")) {
212 appendError("The 'atoms' key does not contain an 'elements' key.");
213 return false;
214 }
215
216 if (atoms.contains("elements") && !atoms["elements"].is_object()) {
217 appendError("The 'elements' key does not contain an object.");
218 return false;
219 }
220
221 json elements = atoms["elements"];
222 if (!elements.contains("number")) {
223 appendError("The 'elements' key does not contain a 'number' key.");
224 return false;
225 }
226
227 json atomicNumbers = elements["number"];
228 // This represents our minimal spec for a molecule - atoms that have an
229 // atomic number.
230 if (isNumericArray(atomicNumbers) && atomicNumbers.size() > 0) {
231 for (auto& atomicNumber : atomicNumbers) {
232 if (!atomicNumber.is_number_integer() || atomicNumber < 0 ||
233 atomicNumber >= Core::element_count) {
234 appendError("Error: atomic number is invalid.");
235 return false;
236 }
237 molecule.addAtom(atomicNumber);
238 }
239 } else {
240 // we're done, actually - this is an empty file
241 return true;
242 }
243 Index atomCount = molecule.atomCount();
244
245 if (atoms.contains("coords") && atoms["coords"].is_object()) {
246 if (atoms["coords"].contains("3d") && atoms["coords"]["3d"].is_array()) {
247 json atomicCoords = atoms["coords"]["3d"];
248 if (isNumericArray(atomicCoords) &&
249 atomicCoords.size() == 3 * atomCount) {
250 for (Index i = 0; i < atomCount; ++i) {
251 auto a = molecule.atom(i);
252 a.setPosition3d(Vector3(atomicCoords[3 * i], atomicCoords[3 * i + 1],
253 atomicCoords[3 * i + 2]));
254 }
255 }
256 }
257
258 if (atoms["coords"].contains("3dSets")) {
259 // Check for coordinate sets, and read them in if found, e.g.
260 // trajectories.
261 json coordSets = atoms["coords"]["3dSets"];
262 if (coordSets.is_array() && coordSets.size()) {
263 for (unsigned int i = 0; i < coordSets.size(); ++i) {
264 Array<Vector3> setArray;
265 json set = coordSets[i];
266 if (isNumericArray(set)) {
267 for (unsigned int j = 0; j < set.size() / 3; ++j) {
268 setArray.push_back(
269 Vector3(set[3 * j], set[3 * j + 1], set[3 * j + 2]));
270 }
271 molecule.setCoordinate3d(setArray, i);
272 }
273 }
274 // Make sure the first step is active once we are done loading the sets.
275 molecule.setCoordinate3d(0);
276 }
277 }
278 }
279
280 // Array of vector3 for forces if available
281 if (atoms.contains("forces")) {
282 json forces = atoms["forces"];
283 if (isNumericArray(forces) && forces.size() == 3 * atomCount) {
284 for (Index i = 0; i < atomCount; ++i) {
285 auto a = molecule.atom(i);
286 a.setForceVector(
287 Vector3(forces[3 * i], forces[3 * i + 1], forces[3 * i + 2]));
288 }
289 }
290 }
291
292 // labels
293 if (atoms.contains("labels")) {
294 json labels = atoms["labels"];
295 if (labels.is_array() && labels.size() == atomCount) {
296 for (size_t i = 0; i < atomCount; ++i) {
297 molecule.setAtomLabel(i, labels[i]);
298 }
299 }
300 }
301
302 // formal charges
303 if (atoms.contains("formalCharges")) {
304 json formalCharges = atoms["formalCharges"];
305 if (formalCharges.is_array() && formalCharges.size() == atomCount) {
306 for (size_t i = 0; i < atomCount; ++i) {
307 molecule.atom(i).setFormalCharge(formalCharges[i]);
308 }
309 }
310 }
311
312 // Read in colors if they are present.
313 if (atoms.contains("colors")) {
314 json colors = atoms["colors"];
315 if (colors.is_array() && colors.size() == 3 * atomCount) {
316 for (Index i = 0; i < atomCount; ++i) {
317 Vector3ub color(colors[3 * i], colors[3 * i + 1], colors[3 * i + 2]);
318 molecule.setColor(i, color);
319 }
320 }
321 }
322
323 if (atoms.contains("properties")) {
324 json atomProperties = atoms["properties"];
325 if (atomProperties.is_object()) {
326 for (auto& property : atomProperties.items()) {
327 if (property.value().is_array()) {
328 // TODO: handle atom properties
329 }
330 }
331 }
332 }
333
334 // Selection is optional, but if present should be loaded.
335 if (atoms.contains("selected")) {
336 json selection = atoms["selected"];
337 if (isBooleanArray(selection) && selection.size() == atomCount)
338 for (Index i = 0; i < atomCount; ++i)
339 molecule.setAtomSelected(i, selection[i]);
340 else if (isNumericArray(selection) && selection.size() == atomCount)
341 for (Index i = 0; i < atomCount; ++i)
342 molecule.setAtomSelected(i, selection[i] != 0);
343 }
344
345 if (atoms.contains("frozen")) {
346 json frozen = atoms["frozen"];
347 if (frozen.is_array() && frozen.size() == atomCount) {
348 for (Index i = 0; i < atomCount; ++i) {
349 bool freeze = false;
350 if (frozen[i].is_number())
351 freeze = (frozen[i] != 0);
352 else if (frozen[i].is_boolean())
353 freeze = frozen[i];
354 molecule.setFrozenAtom(i, freeze);
355 }
356 } // might also be a 3xN array for per-axis freezing
357 else if (frozen.is_array() && frozen.size() == 3 * atomCount) {
358 for (Index i = 0; i < atomCount; ++i) {
359 bool freeze = false;
360 if (frozen[3 * i].is_number())
361 freeze = (frozen[3 * i] != 0);
362 else if (frozen[3 * i].is_boolean())
363 freeze = frozen[3 * i];
364 molecule.setFrozenAtomAxis(i, 0, freeze);
365
366 if (frozen[3 * i + 1].is_number())
367 freeze = (frozen[3 * i + 1] != 0);
368 else if (frozen[3 * i + 1].is_boolean())
369 freeze = frozen[3 * i + 1];
370 molecule.setFrozenAtomAxis(i, 1, freeze);
371
372 if (frozen[3 * i + 2].is_number())
373 freeze = (frozen[3 * i + 2] != 0);
374 else if (frozen[3 * i + 2].is_boolean())
375 freeze = frozen[3 * i + 2];
376 molecule.setFrozenAtomAxis(i, 2, freeze);
377 }
378 }
379 }
380
381 if (atoms.find("layer") != atoms.end()) {
382 json layerJson = atoms["layer"];
383 if (isNumericArray(layerJson)) {
384 auto& layer = LayerManager::getMoleculeInfo(&molecule)->layer;
385 for (Index i = 0; i < atomCount && i < layerJson.size(); ++i) {
386 while (layerJson[i] > layer.maxLayer()) {
387 layer.addLayer();
388 }
389 layer.addAtom(layerJson[i], i);
390 }
391 }
392 }
393
394 // look for isotopes if present
395 if (atoms.contains("isotopes")) {
396 json isotopes = atoms["isotopes"];
397 if (isNumericArray(isotopes) && isotopes.size() == atomCount) {
398 for (Index i = 0; i < atomCount; ++i)
399 molecule.setIsotope(i, isotopes[i]);
400 }
401 }
402
403 // Bonds are optional, but if present should be loaded.
404 if (jsonRoot.contains("bonds")) {
405 json bonds = jsonRoot["bonds"];
406 if (bonds.is_object() && isNumericArray(bonds["connections"]["index"])) {
407 json connections = bonds["connections"]["index"];
408 for (unsigned int i = 0; i < connections.size() / 2; ++i) {
409 Index atom1 = static_cast<Index>(connections[2 * i]);
410 Index atom2 = static_cast<Index>(connections[2 * i + 1]);
411 if (atom1 < atomCount && atom2 < atomCount &&
412 atom1 != atom2) { // avoid self-bonds
413 molecule.addBond(atom1, atom2, 1);
414 }
415 }
416 if (bonds.contains("order")) {
417 json order = bonds["order"];
418 if (isNumericArray(order)) {
419 for (unsigned int i = 0; i < molecule.bondCount() && i < order.size();
420 ++i) {
421 int bondOrder = static_cast<int>(order[i]);
422 if (bondOrder < 1 || bondOrder > 6) {
423 appendError("Error: bond order is invalid.");
424 return false;
425 }
426
427 molecule.bond(i).setOrder(bondOrder);
428 }
429 }
430 }
431
432 // are there bond labels?
433 if (bonds.contains("labels")) {
434 json bondLabels = bonds["labels"];
435 if (bondLabels.is_array()) {
436 for (unsigned int i = 0;
437 i < molecule.bondCount() && i < bondLabels.size(); ++i) {
438 molecule.setBondLabel(i, bondLabels[i]);
439 }
440 }
441 }
442
443 if (bonds.contains("properties")) {
444 json bondProperties = bonds["properties"];
445 if (bondProperties.is_object()) {
446 for (auto& property : bondProperties.items()) {
447 if (property.value().is_array()) {
448 // TODO: handle bond properties
449 }
450 }
451 }
452 }
453 }
454 }
455
456 // residues are optional, but should be loaded
457 if (jsonRoot.contains("residues")) {
458 json residues = jsonRoot["residues"];
459 if (residues.is_array()) {
460 for (auto residue : residues) {
461 if (!residue.is_object())
462 continue; // malformed
463
464 // Validate required fields exist and have correct types
465 if (!residue.contains("name") || !residue["name"].is_string())
466 continue;
467 if (!residue.contains("id") || !residue["id"].is_number_integer())
468 continue;
469 if (!residue.contains("chainId") ||
470 !residue["chainId"].is_number_integer())
471 continue;
472
473 auto name = residue["name"].get<std::string>();
474 auto id = static_cast<Index>(residue["id"]);
475 auto chainId = static_cast<char>(residue["chainId"].get<int>());
476 Residue newResidue(name, id, chainId);
477
478 if (residue.contains("hetero") && residue["hetero"] == true)
479 newResidue.setHeterogen(true);
480
481 int secStruct = residue.value("secStruct", -1);
482 if (secStruct != -1)
483 newResidue.setSecondaryStructure(
484 static_cast<Avogadro::Core::Residue::SecondaryStructure>(
485 secStruct));
486
487 if (residue.contains("atoms") && residue["atoms"].is_object()) {
488 json atomsResidue = residue["atoms"];
489 for (auto& item : atomsResidue.items()) {
490 if (item.value().is_number_integer() &&
491 static_cast<Index>(item.value()) < molecule.atomCount()) {
492 const Atom& atom =
493 molecule.atom(static_cast<Index>(item.value()));
494 newResidue.addResidueAtom(item.key(), atom);
495 }
496 }
497 }
498 if (residue.contains("color") && residue["color"].is_array() &&
499 residue["color"].size() == 3 && isNumericArray(residue["color"])) {
500 json color = residue["color"];
501 Vector3ub col = Vector3ub(color[0], color[1], color[2]);
502 newResidue.setColor(col);
503 }
504
505 molecule.addResidue(newResidue);
506
507 if (residue.contains("label") && residue["label"].is_string())
508 molecule.setResidueLabel(molecule.residueCount() - 1,
509 residue["label"]);
510 }
511 }
512 }
513
514 if (jsonRoot.contains("unitCell") || jsonRoot.contains("unit cell")) {
515 json unitCell = jsonRoot["unitCell"];
516 if (!unitCell.is_object())
517 unitCell = jsonRoot["unit cell"];
518
519 if (unitCell.is_object()) {
520 Core::UnitCell* unitCellObject = nullptr;
521
522 // read in cell vectors in preference to a, b, c parameters
523 json cellVectors = unitCell["cellVectors"];
524 if (cellVectors.is_array() && cellVectors.size() == 9 &&
525 isNumericArray(cellVectors)) {
526 Vector3 aVector(cellVectors[0], cellVectors[1], cellVectors[2]);
527 Vector3 bVector(cellVectors[3], cellVectors[4], cellVectors[5]);
528 Vector3 cVector(cellVectors[6], cellVectors[7], cellVectors[8]);
529 unitCellObject = new Core::UnitCell(aVector, bVector, cVector);
530 if (!unitCellObject->isRegular()) {
531 appendError("cellVectors are not linear independent");
532 delete unitCellObject;
533 return false;
534 }
535 } else if (unitCell["a"].is_number() && unitCell["b"].is_number() &&
536 unitCell["c"].is_number() && unitCell["alpha"].is_number() &&
537 unitCell["beta"].is_number() &&
538 unitCell["gamma"].is_number()) {
539 Real a = static_cast<Real>(unitCell["a"]);
540 Real b = static_cast<Real>(unitCell["b"]);
541 Real c = static_cast<Real>(unitCell["c"]);
542 Real alpha = static_cast<Real>(unitCell["alpha"]) * DEG_TO_RAD;
543 Real beta = static_cast<Real>(unitCell["beta"]) * DEG_TO_RAD;
544 Real gamma = static_cast<Real>(unitCell["gamma"]) * DEG_TO_RAD;
545 unitCellObject = new Core::UnitCell(a, b, c, alpha, beta, gamma);
546 if (!unitCellObject->isRegular()) {
547 appendError(
548 "cell parameters do not give linear-independent lattice vectors");
549 delete unitCellObject;
550 return false;
551 }
552 }
553 if (unitCellObject != nullptr) {
554 molecule.setUnitCell(unitCellObject);
555
556 // check for Hall number if present
557 if (unitCell["hallNumber"].is_number()) {
558 auto hallNumber = static_cast<int>(unitCell["hallNumber"]);
559 if (hallNumber > 0 && hallNumber < 531)
560 molecule.setHallNumber(hallNumber);
561 } else if (unitCell["spaceGroup"].is_string()) {
562 auto hallNumber =
563 Core::SpaceGroups::hallNumber(unitCell["spaceGroup"]);
564 if (hallNumber != 0)
565 molecule.setHallNumber(hallNumber);
566 }
567 }
568 }
569 }
570
571 if (atoms["coords"].contains("3dFractional") ||
572 atoms["coords"].contains("3d fractional")) {
573 json fractional = atoms["coords"]["3dFractional"];
574 if (!fractional.is_array())
575 fractional = atoms["coords"]["3d fractional"];
576 if (fractional.is_array() && fractional.size() == 3 * atomCount &&
577 isNumericArray(fractional) && molecule.unitCell()) {
578 Array<Vector3> fcoords;
579 fcoords.reserve(atomCount);
580 for (Index i = 0; i < atomCount; ++i) {
581 fcoords.push_back(Vector3(static_cast<Real>(fractional[i * 3 + 0]),
582 static_cast<Real>(fractional[i * 3 + 1]),
583 static_cast<Real>(fractional[i * 3 + 2])));
584 }
585 CrystalTools::setFractionalCoordinates(molecule, fcoords);
586 }
587 }
588
589 // Basis set is optional, if present read it in.
590 if (jsonRoot.contains("basisSet")) {
591 json basisSet = jsonRoot["basisSet"];
592 if (basisSet.is_object()) {
593 auto* basis = new GaussianSet;
594 basis->setMolecule(&molecule);
595 // Gather the relevant pieces together so that they can be read in.
596 json shellTypes = basisSet["shellTypes"];
597 json primitivesPerShell = basisSet["primitivesPerShell"];
598 json shellToAtomMap = basisSet["shellToAtomMap"];
599 json exponents = basisSet["exponents"];
600 json coefficients = basisSet["coefficients"];
601
602 int nGTO = 0;
603 for (unsigned int i = 0; i < shellTypes.size(); ++i) {
604 GaussianSet::orbital type;
605 switch (static_cast<int>(shellTypes[i])) {
606 case 0:
607 type = GaussianSet::S;
608 break;
609 case 1:
610 type = GaussianSet::P;
611 break;
612 case 2:
613 type = GaussianSet::D;
614 break;
615 case -2:
616 type = GaussianSet::D5;
617 break;
618 case 3:
619 type = GaussianSet::F;
620 break;
621 case -3:
622 type = GaussianSet::F7;
623 break;
624 case 4:
625 type = GaussianSet::G;
626 break;
627 case -4:
628 type = GaussianSet::G9;
629 break;
630 default:
631 // If we encounter GTOs we do not understand, the basis is likely
632 // invalid
633 type = GaussianSet::UU;
634 }
635 if (type != GaussianSet::UU) {
636 int b = basis->addBasis(static_cast<int>(shellToAtomMap[i]), type);
637 for (int j = 0; j < static_cast<int>(primitivesPerShell[i]); ++j) {
638 basis->addGto(b, coefficients[nGTO], exponents[nGTO]);
639 ++nGTO;
640 }
641 }
642 }
643
644 json orbitals = jsonRoot["orbitals"];
645 if (orbitals.is_object() && basis->isValid()) {
646 basis->setElectronCount(orbitals["electronCount"]);
647 json occupations = orbitals["occupations"];
648 if (isNumericArray(occupations)) {
649 std::vector<unsigned char> occs;
650 for (auto& occupation : occupations)
651 occs.push_back(static_cast<unsigned char>(occupation));
652 basis->setMolecularOrbitalOccupancy(occupations);
653 }
654 json energies = orbitals["energies"];
655 if (isNumericArray(energies)) {
656 std::vector<double> energyArray;
657 for (auto& energie : energies)
658 energyArray.push_back(static_cast<double>(energie));
659 basis->setMolecularOrbitalEnergy(energyArray);
660 }
661 json numbers = orbitals["numbers"];
662 if (isNumericArray(numbers)) {
663 std::vector<unsigned int> numArray;
664 for (auto& number : numbers)
665 numArray.push_back(static_cast<unsigned int>(number));
666 basis->setMolecularOrbitalNumber(numArray);
667 }
668 json symmetryLabels = orbitals["symmetries"];
669 if (symmetryLabels.is_array()) {
670 std::vector<std::string> symArray;
671 for (auto& sym : symmetryLabels)
672 symArray.push_back(sym);
673 basis->setSymmetryLabels(symArray);
674 }
675 json moCoefficients = orbitals["moCoefficients"];
676 json moCoefficientsA = orbitals["alphaCoefficients"];
677 json moCoefficientsB = orbitals["betaCoefficients"];
678 bool openShell = false;
679 if (isNumericArray(moCoefficients)) {
680 std::vector<double> coeffs;
681 for (auto& moCoefficient : moCoefficients)
682 coeffs.push_back(static_cast<double>(moCoefficient));
683 basis->setMolecularOrbitals(coeffs);
684 } else if (isNumericArray(moCoefficientsA) &&
685 isNumericArray(moCoefficientsB)) {
686 std::vector<double> coeffsA;
687 for (auto& i : moCoefficientsA)
688 coeffsA.push_back(static_cast<double>(i));
689 std::vector<double> coeffsB;
690 for (auto& i : moCoefficientsB)
691 coeffsB.push_back(static_cast<double>(i));
692 basis->setMolecularOrbitals(coeffsA, BasisSet::Alpha);
693 basis->setMolecularOrbitals(coeffsB, BasisSet::Beta);
694 openShell = true;
695 } else {
696 std::cout << "No orbital cofficients found!" << std::endl;
697 }
698 // Check for orbital coefficient sets, these are paired with coordinates
699 // when they exist, but have constant basis set, atom types, etc.
700 if (orbitals["sets"].is_array() && orbitals["sets"].size()) {
701 json orbSets = orbitals["sets"];
702 for (unsigned int idx = 0; idx < orbSets.size(); ++idx) {
703 moCoefficients = orbSets[idx]["moCoefficients"];
704 moCoefficientsA = orbSets[idx]["alphaCoefficients"];
705 moCoefficientsB = orbSets[idx]["betaCoefficients"];
706 if (isNumericArray(moCoefficients)) {
707 std::vector<double> coeffs;
708 for (auto& moCoefficient : moCoefficients)
709 coeffs.push_back(static_cast<double>(moCoefficient));
710 basis->setMolecularOrbitals(coeffs, BasisSet::Paired, idx);
711 } else if (isNumericArray(moCoefficientsA) &&
712 isNumericArray(moCoefficientsB)) {
713 std::vector<double> coeffsA;
714 for (auto& i : moCoefficientsA)
715 coeffsA.push_back(static_cast<double>(i));
716 std::vector<double> coeffsB;
717 for (auto& i : moCoefficientsB)
718 coeffsB.push_back(static_cast<double>(i));
719 basis->setMolecularOrbitals(coeffsA, BasisSet::Alpha, idx);
720 basis->setMolecularOrbitals(coeffsB, BasisSet::Beta, idx);
721 openShell = true;
722 }
723 }
724 // Set the first step as active.
725 basis->setActiveSetStep(0);
726 }
727 if (openShell) {
728 // look for alpha and beta orbital energies
729 json energiesA = orbitals["alphaEnergies"];
730 json energiesB = orbitals["betaEnergies"];
731 // check if they are numeric arrays
732 if (isNumericArray(energiesA) && isNumericArray(energiesB)) {
733 std::vector<double> moEnergiesA;
734 for (auto& i : energiesA)
735 moEnergiesA.push_back(static_cast<double>(i));
736 std::vector<double> moEnergiesB;
737 for (auto& i : energiesB)
738 moEnergiesB.push_back(static_cast<double>(i));
739 basis->setMolecularOrbitalEnergy(moEnergiesA, BasisSet::Alpha);
740 basis->setMolecularOrbitalEnergy(moEnergiesB, BasisSet::Beta);
741
742 // look for alpha and beta orbital occupations
743 json occupationsA = orbitals["alphaOccupations"];
744 json occupationsB = orbitals["betaOccupations"];
745 // check if they are numeric arrays
746 if (isNumericArray(occupationsA) && isNumericArray(occupationsB)) {
747 std::vector<unsigned char> moOccupationsA;
748 for (auto& i : occupationsA)
749 moOccupationsA.push_back(static_cast<unsigned char>(i));
750 std::vector<unsigned char> moOccupationsB;
751 for (auto& i : occupationsB)
752 moOccupationsB.push_back(static_cast<unsigned char>(i));
753 basis->setMolecularOrbitalOccupancy(moOccupationsA,
754 BasisSet::Alpha);
755 basis->setMolecularOrbitalOccupancy(moOccupationsB,
756 BasisSet::Beta);
757 }
758 }
759 }
760 }
761 molecule.setBasisSet(basis);
762 }
763 }
764
765 // See if there is any vibration data, load it if so.
766 json vibrations = jsonRoot["vibrations"];
767 if (vibrations.is_object()) {
768 json frequencies = vibrations["frequencies"];
769 if (isNumericArray(frequencies)) {
770 Array<double> freqs;
771 for (auto& frequencie : frequencies) {
772 freqs.push_back(static_cast<double>(frequencie));
773 }
774 molecule.setVibrationFrequencies(freqs);
775 }
776 json intensities = vibrations["intensities"];
777 if (isNumericArray(intensities)) {
778 Array<double> intens;
779 for (auto& intensitie : intensities) {
780 intens.push_back(static_cast<double>(intensitie));
781 }
782 molecule.setVibrationIRIntensities(intens);
783 }
784 json raman = vibrations["ramanIntensities"];
785 if (isNumericArray(raman)) {
786 Array<double> intens;
787 for (auto& i : raman) {
788 intens.push_back(static_cast<double>(i));
789 }
790 molecule.setVibrationRamanIntensities(intens);
791 }
792 json displacements = vibrations["eigenVectors"];
793 if (displacements.is_array()) {
794 Array<Array<Vector3>> disps;
795 for (auto arr : displacements) {
796 if (isNumericArray(arr)) {
797 Array<Vector3> mode;
798 mode.resize(arr.size() / 3);
799 double* ptr = &mode[0][0];
800 for (auto& j : arr) {
801 *(ptr++) = static_cast<double>(j);
802 }
803 disps.push_back(mode);
804 }
805 }
806 molecule.setVibrationLx(disps);
807 }
808 }
809
810 // check for spectra data
811 json spectra = jsonRoot["spectra"];
812 if (spectra.is_object()) {
813 // electronic
814 json electronic = spectra["electronic"];
815 if (electronic.is_object()) {
816 // check to see "energies" and "intensities"
817 json energies = electronic["energies"];
818 json intensities = electronic["intensities"];
819 // make sure they are both numeric arrays
820 if (isNumericArray(energies) && isNumericArray(intensities)) {
821 // make sure they are the same size
822 if (energies.size() == intensities.size()) {
823 // create the matrix
824 MatrixX electronicData(energies.size(), 2);
825 // copy the data
826 for (std::size_t i = 0; i < energies.size(); ++i) {
827 electronicData(i, 0) = energies[i];
828 electronicData(i, 1) = intensities[i];
829 }
830 // set the data
831 molecule.setSpectra("Electronic", electronicData);
832 }
833 }
834 // check if there's CD data for "rotation"
835 json rotation = electronic["rotation"];
836 if (isNumericArray(rotation) && rotation.size() == energies.size()) {
837 MatrixX rotationData(rotation.size(), 2);
838 for (std::size_t i = 0; i < rotation.size(); ++i) {
839 rotationData(i, 0) = energies[i];
840 rotationData(i, 1) = rotation[i];
841 }
842 molecule.setSpectra("CircularDichroism", rotationData);
843 }
844 }
845
846 // nmr
847 json nmr = spectra["nmr"];
848 if (nmr.is_object()) {
849 // chemical shifts
850 json chemicalShifts = nmr["shifts"];
851 if (isNumericArray(chemicalShifts)) {
852 MatrixX chemicalShiftData(chemicalShifts.size(), 2);
853 for (std::size_t i = 0; i < chemicalShifts.size(); ++i) {
854 chemicalShiftData(i, 0) = static_cast<double>(chemicalShifts[i]);
855 chemicalShiftData(i, 1) = 1.0;
856 }
857 molecule.setSpectra("NMR", chemicalShiftData);
858 }
859 }
860 }
861
862 // constraints
863 if (jsonRoot.find("constraints") != jsonRoot.end()) {
864 json constraints = jsonRoot["constraints"];
865 if (constraints.is_array()) {
866 for (auto& constraint : constraints) {
867 if (isNumericArray(constraint)) {
868 // value, atom1, atom2, atom3, atom4
869 if (constraint.size() == 3) { // bond
870 molecule.addConstraint(constraint[0], constraint[1], constraint[2]);
871 } else if (constraint.size() == 4) { // angle
872 molecule.addConstraint(constraint[0], constraint[1], constraint[2],
873 constraint[3]);
874 } else if (constraint.size() == 5) { // torsion
875 molecule.addConstraint(constraint[0], constraint[1], constraint[2],
876 constraint[3], constraint[4]);
877 }
878 }
879 }
880 }
881 }
882
883 // properties
884 if (jsonRoot.find("properties") != jsonRoot.end()) {
885 json properties = jsonRoot["properties"];
886 if (properties.is_object()) {
887 if (properties.find("totalCharge") != properties.end()) {
888 molecule.setData("totalCharge",
889 static_cast<int>(properties["totalCharge"]));
890 }
891 if (properties.find("totalSpinMultiplicity") != properties.end()) {
892 molecule.setData("totalSpinMultiplicity",
893 static_cast<int>(properties["totalSpinMultiplicity"]));
894 }
895 if (properties.find("dipoleMoment") != properties.end()) {
896 // read the numeric array
897 json dipole = properties["dipoleMoment"];
898 if (isNumericArray(dipole) && dipole.size() == 3) {
899 Core::Variant dipoleMoment(dipole[0], dipole[1], dipole[2]);
900 molecule.setData("dipoleMoment", dipoleMoment);
901 }
902 }
903 // iterate through everything else
904 for (auto& element : properties.items()) {
905 if (element.key() == "totalCharge" ||
906 element.key() == "totalSpinMultiplicity" ||
907 element.key() == "dipoleMoment") {
908 continue;
909 }
910 if (element.value().type() == json::value_t::array) {
911 // check if it is a numeric array to go into Eigen::MatrixXd
912 json j = element.value(); // convenience
913 std::size_t rows = j.size();
914 MatrixX matrix;
915 matrix.resize(rows, 1); // default to 1 columns
916 bool isNumeric = true;
917
918 for (std::size_t row = 0; row < j.size(); ++row) {
919 const auto& jrow = j.at(row);
920 // check to see if we have a simple vector or a matrix
921 if (jrow.type() == json::value_t::array) {
922 matrix.conservativeResize(rows, jrow.size());
923 for (std::size_t col = 0; col < jrow.size(); ++col) {
924 const auto& value = jrow.at(col);
925 if (value.type() == json::value_t::number_float ||
926 value.type() == json::value_t::number_integer ||
927 value.type() == json::value_t::number_unsigned)
928 matrix(row, col) = value.get<double>();
929 else {
930 isNumeric = false;
931 break;
932 }
933 }
934 } else if (jrow.type() == json::value_t::number_float ||
935 jrow.type() == json::value_t::number_integer ||
936 jrow.type() == json::value_t::number_unsigned) {
937 // just a row vector
938 matrix(row, 0) = jrow.get<double>();
939 } else {
940 isNumeric = false;
941 break;
942 }
943 }
944 if (isNumeric)
945 molecule.setData(element.key(), matrix);
946 // TODO: add support for non-numeric arrays
947 // std::cout << " property: " << element.key() << " = " << matrix
948 // << " size " << matrix.rows() << 'x' << matrix.cols()
949 // << std::endl;
950 } else if (element.value().type() == json::value_t::number_float) {
951 molecule.setData(element.key(), element.value().get<double>());
952 } else if (element.value().type() == json::value_t::number_integer) {
953 molecule.setData(element.key(), element.value().get<int>());
954 } else if (element.value().type() == json::value_t::boolean) {
955 molecule.setData(element.key(), element.value().get<bool>());
956 } else if (element.value().type() == json::value_t::string) {
957 molecule.setData(element.key(), element.value().get<std::string>());
958 } else {
959 std::cout << " cannot store property: " << element.key() << " = "
960 << element.value() << " type "
961 << element.value().type_name() << std::endl;
962 }
963 }
964 }
965 }
966
967 // inputParameters are calculation metadata
968 if (jsonRoot.find("inputParameters") != jsonRoot.end()) {
969 json inputParameters = jsonRoot["inputParameters"];
970 // add this as a string to the molecule data
971 molecule.setData("inputParameters", inputParameters.dump());
972 }
973
974 // Partial charges are optional, but if present should be loaded.
975 json partialCharges;
976 if (atoms.contains("partialCharges")) {
977 partialCharges = atoms["partialCharges"];
978 }
979 // some inconsistent files have it as part of the root
980 if (jsonRoot.contains("partialCharges")) {
981 partialCharges = jsonRoot["partialCharges"];
982 }
983 if (partialCharges.is_object()) {
984 // keys are types, values are arrays of charges
985 for (auto& kv : partialCharges.items()) {
986 MatrixX charges(atomCount, 1);
987 if (isNumericArray(kv.value()) && kv.value().size() == atomCount) {
988 for (size_t i = 0; i < kv.value().size(); ++i) {
989 charges(i, 0) = kv.value()[i];
990 }
991 molecule.setPartialCharges(kv.key(), charges);
992 }
993 }
994 }
995
996 // look for possible cube data
997 if (jsonRoot.find("cube") != jsonRoot.end()) {
998 json cubeObj = jsonRoot["cube"];
999 // get the limits
1000 Vector3 min, max, delta;
1001 Vector3i points;
1002 json origin = cubeObj["origin"];
1003 json spacing = cubeObj["spacing"];
1004 json dimensions = cubeObj["dimensions"];
1005 json type = cubeObj["type"];
1006
1007 if (isNumericArray(origin) && origin.size() == 3 &&
1008 isNumericArray(spacing) && spacing.size() == 3 &&
1009 isNumericArray(dimensions) && dimensions.size() == 3) {
1010 Cube* cube = molecule.addCube();
1011
1012 // types
1013 if (type == "vdw")
1014 cube->setCubeType(Cube::VdW);
1015 else if (type == "solventAccessible")
1016 cube->setCubeType(Cube::SolventAccessible);
1017 else if (type == "solventExcluded")
1018 cube->setCubeType(Cube::SolventExcluded);
1019 else if (type == "esp")
1020 cube->setCubeType(Cube::ESP);
1021 else if (type == "electronDensity")
1022 cube->setCubeType(Cube::ElectronDensity);
1023 else if (type == "spinDensity")
1024 cube->setCubeType(Cube::SpinDensity);
1025 else if (type == "mo")
1026 cube->setCubeType(Cube::MO);
1027 else
1028 cube->setCubeType(Cube::FromFile);
1029
1030 if (cubeObj.find("name") != cubeObj.end())
1031 cube->setName(cubeObj["name"]);
1032
1033 min = Vector3(origin[0], origin[1], origin[2]);
1034 points = Vector3i(dimensions[0], dimensions[1], dimensions[2]);
1035 delta = Vector3(spacing[0], spacing[1], spacing[2]);
1036 max = Vector3(min[0] + (points[0] - 1) * delta[0],
1037 min[1] + (points[1] - 1) * delta[1],
1038 min[2] + (points[2] - 1) * delta[2]);
1039
1040 cube->setLimits(min, max, points);
1041 // check the length of the scalar array
1042 unsigned int expectedSize = points[0] * points[1] * points[2];
1043 if (isNumericArray(cubeObj["scalars"]) &&
1044 cubeObj["scalars"].size() == expectedSize) {
1045 cube->setData(cubeObj["scalars"]);
1046 }
1047 }
1048 }
1049
1050 if (jsonRoot.find("layer") != jsonRoot.end()) {
1051 auto names = LayerManager::getMoleculeInfo(&molecule);
1052 json visible = jsonRoot["layer"]["visible"];
1053 if (isBooleanArray(visible)) {
1054 for (const auto& v : visible) {
1055 names->visible.push_back(v);
1056 }
1057 }
1058 json locked = jsonRoot["layer"]["locked"];
1059 if (isBooleanArray(locked)) {
1060 for (const auto& l : locked) {
1061 names->locked.push_back(l);
1062 }
1063 }
1064
1065 json enables = jsonRoot["layer"]["enable"];
1066 if (enables.is_object()) {
1067 for (const auto& enable : enables.items()) {
1068 if (isBooleanArray(enable.value())) {
1069 names->enable[enable.key()] = std::vector<bool>();
1070 for (const auto& e : enable.value()) {
1071 names->enable[enable.key()].push_back(e);
1072 }
1073 }
1074 }
1075 }
1076
1077 json settings = jsonRoot["layer"]["settings"];
1078 if (settings.is_object()) {
1079 for (const auto& setting : settings.items()) {
1080 if (isBooleanArray(setting.value())) {
1081 names->settings[setting.key()] = Core::Array<LayerData*>();
1082 for (const auto& s : setting.value()) {
1083 names->settings[setting.key()].push_back(new LayerData(s));
1084 }
1085 }
1086 }
1087 }
1088 }
1089
1090 return true;
1091 }
1092
1093 bool CjsonFormat::write(std::ostream& file, const Molecule& molecule)
1094 {
1095 return serialize(file, molecule, true);
1096 }
1097
1098 bool CjsonFormat::serialize(std::ostream& file, const Molecule& molecule,
1099 bool isJson)
1100 {
1101 json opts;
1102 if (!options().empty())
1103 opts = json::parse(options(), nullptr, false);
1104 else
1105 opts = json::object();
1106
1107 ordered_json root;
1108
1109 root["chemicalJson"] = 1;
1110
1111 if (opts.value("properties", true)) {
1112 if (molecule.data("name").type() == Variant::String)
1113 root["name"] = molecule.data("name").toString().c_str();
1114 if (molecule.data("inchi").type() == Variant::String)
1115 root["inchi"] = molecule.data("inchi").toString().c_str();
1116 }
1117
1118 json properties;
1119 // these methods assume neutral singlet if not set
1120 // or approximate from formal charges and # of electrons
1121 properties["totalCharge"] = molecule.totalCharge();
1122 properties["totalSpinMultiplicity"] = molecule.totalSpinMultiplicity();
1123 // loop through all other properties
1124 const auto map = molecule.dataMap();
1125 for (const auto& element : map) {
1126 if (element.first == "name" || element.first == "inchi")
1127 continue;
1128
1129 // check for "inputParameters" and handle it separately
1130 if (element.first == "inputParameters") {
1131 json inputParameters = json::parse(element.second.toString());
1132 root["inputParameters"] = inputParameters;
1133 continue;
1134 }
1135
1136 // check if the key is atom.* or bond.* and handle it separately
1137 if (element.first.find("atom.") == 0 || element.first.find("bond.") == 0 ||
1138 element.first.find("residue.") == 0) {
1139 continue;
1140 }
1141
1142 if (element.second.type() == Variant::String)
1143 properties[element.first] = element.second.toString().c_str();
1144 else if (element.second.type() == Variant::Double)
1145 properties[element.first] = element.second.toDouble();
1146 else if (element.second.type() == Variant::Float)
1147 properties[element.first] = element.second.toFloat();
1148 else if (element.second.type() == Variant::Int)
1149 properties[element.first] = element.second.toInt();
1150 else if (element.second.type() == Variant::Bool)
1151 properties[element.first] = element.second.toBool();
1152 else if (element.second.type() == Variant::Vector) {
1153 // e.g. dipole moment
1154 Vector3 v = element.second.toVector3();
1155 json vector;
1156 vector.push_back(v.x());
1157 vector.push_back(v.y());
1158 vector.push_back(v.z());
1159 properties[element.first] = vector;
1160 } else if (element.second.type() == Variant::Matrix) {
1161 MatrixX m = element.second.toMatrix();
1162 json matrix;
1163 for (int i = 0; i < m.rows(); ++i) {
1164 json row;
1165 for (int j = 0; j < m.cols(); ++j) {
1166 row.push_back(m(i, j));
1167 }
1168 matrix.push_back(row);
1169 }
1170 properties[element.first] = matrix;
1171 }
1172 }
1173 root["properties"] = properties;
1174
1175 if (molecule.unitCell()) {
1176 json unitCell;
1177 unitCell["a"] = molecule.unitCell()->a();
1178 unitCell["b"] = molecule.unitCell()->b();
1179 unitCell["c"] = molecule.unitCell()->c();
1180 unitCell["alpha"] = molecule.unitCell()->alpha() * RAD_TO_DEG;
1181 unitCell["beta"] = molecule.unitCell()->beta() * RAD_TO_DEG;
1182 unitCell["gamma"] = molecule.unitCell()->gamma() * RAD_TO_DEG;
1183
1184 json vectors;
1185 vectors.push_back(molecule.unitCell()->aVector().x());
1186 vectors.push_back(molecule.unitCell()->aVector().y());
1187 vectors.push_back(molecule.unitCell()->aVector().z());
1188
1189 vectors.push_back(molecule.unitCell()->bVector().x());
1190 vectors.push_back(molecule.unitCell()->bVector().y());
1191 vectors.push_back(molecule.unitCell()->bVector().z());
1192
1193 vectors.push_back(molecule.unitCell()->cVector().x());
1194 vectors.push_back(molecule.unitCell()->cVector().y());
1195 vectors.push_back(molecule.unitCell()->cVector().z());
1196 unitCell["cellVectors"] = vectors;
1197
1198 // write the Hall number and space group
1199 unitCell["hallNumber"] = molecule.hallNumber();
1200 unitCell["spaceGroup"] =
1201 Core::SpaceGroups::international(molecule.hallNumber());
1202
1203 root["unitCell"] = unitCell;
1204 }
1205
1206 // check for spectra data
1207 // vibrations are separate
1208 if (molecule.spectraTypes().size() != 0) {
1209 json spectra, electronic, nmr;
1210 bool hasElectronic = false;
1211 for (const auto& type : molecule.spectraTypes()) {
1212 if (type == "Electronic") {
1213 hasElectronic = true;
1214 electronic["energies"] = eigenColToJson(molecule.spectra(type), 0);
1215 electronic["intensities"] = eigenColToJson(molecule.spectra(type), 1);
1216 } else if (type == "CircularDichroism") {
1217 electronic["rotation"] = eigenColToJson(molecule.spectra(type), 1);
1218 } else if (type == "NMR") {
1219 json data;
1220 data["shifts"] = eigenColToJson(molecule.spectra(type), 0);
1221 spectra["nmr"] = data;
1222 }
1223 }
1224 if (hasElectronic) {
1225 spectra["electronic"] = electronic;
1226 }
1227 root["spectra"] = spectra;
1228 }
1229
1230 // Create a basis set/MO matrix we can round trip.
1231 if (molecule.basisSet() &&
1232 dynamic_cast<const GaussianSet*>(molecule.basisSet())) {
1233 json basis;
1234 auto gaussian = dynamic_cast<const GaussianSet*>(molecule.basisSet());
1235
1236 // Map the shell types from enumeration to integer values.
1237 auto symmetry = gaussian->symmetry();
1238 json shellTypes;
1239 for (int i : symmetry) {
1240 switch (i) {
1241 case GaussianSet::S:
1242 shellTypes.push_back(0);
1243 break;
1244 case GaussianSet::P:
1245 shellTypes.push_back(1);
1246 break;
1247 case GaussianSet::D:
1248 shellTypes.push_back(2);
1249 break;
1250 case GaussianSet::D5:
1251 shellTypes.push_back(-2);
1252 break;
1253 case GaussianSet::F:
1254 shellTypes.push_back(3);
1255 break;
1256 case GaussianSet::F7:
1257 shellTypes.push_back(-3);
1258 break;
1259 case GaussianSet::G:
1260 shellTypes.push_back(4);
1261 break;
1262 case GaussianSet::G9:
1263 shellTypes.push_back(-4);
1264 break;
1265 default:
1266 // Something bad, put in a silly number...
1267 shellTypes.push_back(426942);
1268 }
1269 }
1270 basis["shellTypes"] = shellTypes;
1271
1272 // This bit is slightly tricky, map from our index to primitives per
1273 // shell.
1274 if (gaussian->gtoIndices().size() && gaussian->atomIndices().size()) {
1275 auto gtoIndices = gaussian->gtoIndices();
1276 auto gtoA = gaussian->gtoA();
1277 json primitivesPerShell;
1278 for (size_t i = 0; i < gtoIndices.size() - 1; ++i)
1279 primitivesPerShell.push_back(gtoIndices[i + 1] - gtoIndices[i]);
1280 primitivesPerShell.push_back(gtoA.size() - gtoIndices.back());
1281 basis["primitivesPerShell"] = primitivesPerShell;
1282
1283 auto atomIndices = gaussian->atomIndices();
1284 json shellToAtomMap;
1285 for (unsigned int& atomIndice : atomIndices)
1286 shellToAtomMap.push_back(atomIndice);
1287 basis["shellToAtomMap"] = shellToAtomMap;
1288
1289 auto gtoC = gaussian->gtoC();
1290 json exponents;
1291 json coefficients;
1292 for (size_t i = 0; i < gtoA.size(); ++i) {
1293 exponents.push_back(gtoA[i]);
1294 coefficients.push_back(gtoC[i]);
1295 }
1296 basis["exponents"] = exponents;
1297 basis["coefficients"] = coefficients;
1298
1299 // Write out the basis set if a valid one exists.
1300 root["basisSet"] = basis;
1301 }
1302
1303 // Now get the MO matrix, potentially other things. Need to get a handle
1304 // on when we have just one (paired), or two (alpha and beta) to write.
1305 auto moMatrix = gaussian->moMatrix();
1306 auto betaMatrix = gaussian->moMatrix(BasisSet::Beta);
1307 json moCoefficients;
1308 for (int j = 0; j < moMatrix.cols(); ++j)
1309 for (int i = 0; i < moMatrix.rows(); ++i)
1310 moCoefficients.push_back(moMatrix(i, j));
1311
1312 if (betaMatrix.cols() > 0 && betaMatrix.rows() > 0) {
1313 json moBeta;
1314 for (int j = 0; j < moMatrix.cols(); ++j)
1315 for (int i = 0; i < moMatrix.rows(); ++i)
1316 moBeta.push_back(moMatrix(i, j));
1317
1318 root["orbitals"]["alphaCoefficients"] = moCoefficients;
1319 root["orbitals"]["betaCoefficients"] = moBeta;
1320 } else {
1321 root["orbitals"]["moCoefficients"] = moCoefficients;
1322 }
1323
1324 // Some energy, occupation, and number data potentially.
1325 auto energies = gaussian->moEnergy();
1326 if (energies.size() > 0) {
1327 json energyData;
1328 for (double& energie : energies) {
1329 energyData.push_back(energie);
1330 }
1331
1332 auto betaEnergies = gaussian->moEnergy(BasisSet::Beta);
1333 if (betaEnergies.size() > 0) {
1334 json betaEnergyData;
1335 for (double& energie : betaEnergies) {
1336 betaEnergyData.push_back(energie);
1337 }
1338 root["orbitals"]["alphaEnergies"] = energyData;
1339 root["orbitals"]["betaEnergies"] = betaEnergyData;
1340 } else
1341 root["orbitals"]["energies"] = energyData;
1342 }
1343 auto occ = gaussian->moOccupancy();
1344 if (occ.size() > 0) {
1345 json occData;
1346 for (unsigned char& it : occ)
1347 occData.push_back(static_cast<int>(it));
1348
1349 auto betaOcc = gaussian->moOccupancy(BasisSet::Beta);
1350 if (betaOcc.size() > 0) {
1351 json betaOccData;
1352 for (unsigned char& it : betaOcc)
1353 betaOccData.push_back(static_cast<int>(it));
1354 root["orbitals"]["alphaOccupations"] = occData;
1355 root["orbitals"]["betaOccupations"] = betaOccData;
1356 } else
1357 root["orbitals"]["occupations"] = occData;
1358 }
1359 auto num = gaussian->moNumber();
1360 if (num.size() > 0) {
1361 json numData;
1362 for (unsigned int& it : num)
1363 numData.push_back(it);
1364 root["orbitals"]["numbers"] = numData;
1365 }
1366
1367 root["orbitals"]["electronCount"] = gaussian->electronCount();
1368 }
1369
1370 // Write out any cubes that are present in the molecule.
1371 if (molecule.cubeCount() > 0) {
1372 json cubeObj;
1373 const Cube* cube = molecule.cube(0);
1374 // Get the origin, max, spacing, and dimensions to place in the object.
1375 json cubeMin;
1376 cubeMin.push_back(cube->min().x());
1377 cubeMin.push_back(cube->min().y());
1378 cubeMin.push_back(cube->min().z());
1379 cubeObj["origin"] = cubeMin;
1380 json cubeSpacing;
1381 cubeSpacing.push_back(cube->spacing().x());
1382 cubeSpacing.push_back(cube->spacing().y());
1383 cubeSpacing.push_back(cube->spacing().z());
1384 cubeObj["spacing"] = cubeSpacing;
1385 json cubeDims;
1386 cubeDims.push_back(cube->dimensions().x());
1387 cubeDims.push_back(cube->dimensions().y());
1388 cubeDims.push_back(cube->dimensions().z());
1389 cubeObj["dimensions"] = cubeDims;
1390
1391 // type
1392 switch (cube->cubeType()) {
1393 case Cube::VdW:
1394 cubeObj["type"] = "vdw";
1395 break;
1396 case Cube::SolventAccessible:
1397 cubeObj["type"] = "solventAccessible";
1398 break;
1399 case Cube::SolventExcluded:
1400 cubeObj["type"] = "solventExcluded";
1401 break;
1402 case Cube::ESP:
1403 cubeObj["type"] = "esp";
1404 break;
1405 case Cube::ElectronDensity:
1406 cubeObj["type"] = "electronDensity";
1407 break;
1408 case Cube::SpinDensity:
1409 cubeObj["type"] = "spinDensity";
1410 break;
1411 case Cube::MO:
1412 cubeObj["type"] = "mo";
1413 break;
1414 case Cube::FromFile:
1415 default:
1416 cubeObj["type"] = "fromFile";
1417 break;
1418 }
1419
1420 // name
1421 cubeObj["name"] = cube->name();
1422
1423 json cubeData;
1424 for (float it : *cube->data()) {
1425 cubeData.push_back(it);
1426 }
1427 cubeObj["scalars"] = cubeData;
1428 root["cube"] = cubeObj;
1429 }
1430
1431 // Create and populate the atom arrays.
1432 if (molecule.atomCount()) {
1433 json atoms;
1434 json elements;
1435 json selected;
1436 json colors;
1437
1438 Vector3ub color;
1439 bool hasCustomColors = molecule.colors().size() == molecule.atomCount();
1440 for (Index i = 0; i < molecule.atomCount(); ++i) {
1441 elements.push_back(molecule.atom(i).atomicNumber());
1442 selected.push_back(molecule.atomSelected(i));
1443
1444 color = molecule.color(i);
1445 colors.push_back(color.x());
1446 colors.push_back(color.y());
1447 colors.push_back(color.z());
1448 }
1449 atoms["elements"]["number"] = elements;
1450 if (!molecule.isSelectionEmpty())
1451 atoms["selected"] = selected;
1452 if (hasCustomColors)
1453 atoms["colors"] = colors;
1454
1455 // check for frozen atoms
1456 json frozen;
1457 // any atoms frozen?
1458 bool anyFrozen = false;
1459 // any atoms with custom axis?
1460 // (i.e., we need to save the matrix)
1461 bool axisFrozen = false;
1462 Eigen::VectorXd frozenAtomMask = molecule.frozenAtomMask();
1463 for (Index i = 0; i < molecule.atomCount(); ++i) {
1464 if (molecule.frozenAtom(i)) {
1465 anyFrozen = true;
1466 frozen.push_back(1);
1467 } else {
1468 frozen.push_back(0);
1469 }
1470
1471 // check for custom axis
1472 if (i * 3 + 2 < frozenAtomMask.size()) {
1473 Real sum = frozenAtomMask[3 * i] + frozenAtomMask[3 * i + 1] +
1474 frozenAtomMask[3 * i + 2];
1475 // check if it's not all frozen or all unfrozen
1476 if (sum != 3.0 && sum != 0.0) {
1477 axisFrozen = true;
1478 }
1479 }
1480 }
1481
1482 if (anyFrozen) {
1483 atoms["frozen"] = frozen;
1484 }
1485 if (axisFrozen) {
1486 // iterate through the mask as an array
1487 json frozenAtomMaskArray;
1488 for (Index i = 0; i < frozenAtomMask.size(); ++i) {
1489 frozenAtomMaskArray.push_back(frozenAtomMask[i]);
1490 }
1491 atoms["frozen"] = frozenAtomMaskArray;
1492 }
1493
1494 // check for partial charges
1495 auto partialCharges = molecule.partialChargeTypes();
1496 if (!partialCharges.empty()) {
1497 // add them to the atoms object
1498 for (const auto& type : partialCharges) {
1499 MatrixX chargesMatrix = molecule.partialCharges(type);
1500 json charges;
1501 for (Index i = 0; i < molecule.atomCount(); ++i) {
1502 charges.push_back(chargesMatrix(i, 0));
1503 }
1504 atoms["partialCharges"][type] = charges;
1505 }
1506 }
1507
1508 json coords;
1509 // 3d positions:
1510 if (molecule.atomPositions3d().size() == molecule.atomCount()) {
1511 // everything gets real-space Cartesians
1512 json coords3d;
1513 for (const auto& it : molecule.atomPositions3d()) {
1514 coords3d.push_back(it.x());
1515 coords3d.push_back(it.y());
1516 coords3d.push_back(it.z());
1517 }
1518 coords["3d"] = coords3d;
1519
1520 // if the unit cell exists, also write fractional coords
1521 if (molecule.unitCell()) {
1522 json coordsFractional;
1523 Array<Vector3> fcoords;
1524 CrystalTools::fractionalCoordinates(
1525 *molecule.unitCell(), molecule.atomPositions3d(), fcoords);
1526 for (auto& fcoord : fcoords) {
1527 coordsFractional.push_back(fcoord.x());
1528 coordsFractional.push_back(fcoord.y());
1529 coordsFractional.push_back(fcoord.z());
1530 }
1531 coords["3dFractional"] = coordsFractional;
1532 }
1533
1534 // if the molecule has multiple coordinate sets, write them out
1535 if (molecule.coordinate3dCount() > 1) {
1536 json coords3dSets;
1537 for (Index i = 0; i < molecule.coordinate3dCount(); ++i) {
1538 json coordsSet;
1539 const auto& positions = molecule.coordinate3d(i);
1540 for (const auto& it : positions) {
1541 coordsSet.push_back(it.x());
1542 coordsSet.push_back(it.y());
1543 coordsSet.push_back(it.z());
1544 }
1545 coords3dSets.push_back(coordsSet);
1546 }
1547 coords["3dSets"] = coords3dSets;
1548 }
1549 }
1550
1551 // 2d positions:
1552 if (molecule.atomPositions2d().size() == molecule.atomCount()) {
1553 json coords2d;
1554 for (const auto& it : molecule.atomPositions2d()) {
1555 coords2d.push_back(it.x());
1556 coords2d.push_back(it.y());
1557 }
1558 coords["2d"] = coords2d;
1559 }
1560 atoms["coords"] = coords;
1561
1562 // forces if present
1563 const auto forceVectors = molecule.forceVectors();
1564 if (forceVectors.size() == molecule.atomCount()) {
1565 json forces;
1566 for (const auto& force : forceVectors) {
1567 forces.push_back(force.x());
1568 forces.push_back(force.y());
1569 forces.push_back(force.z());
1570 }
1571 atoms["forces"] = forces;
1572 }
1573
1574 // check for atom labels
1575 Array atomLabels = molecule.atomLabels();
1576 if (atomLabels.size() == molecule.atomCount()) {
1577 json labels;
1578 for (Index i = 0; i < molecule.atomCount(); ++i) {
1579 labels.push_back(atomLabels[i]);
1580 }
1581 atoms["labels"] = labels;
1582 }
1583
1584 // formal charges
1585 json formalCharges;
1586 bool hasFormalCharges = false;
1587 for (size_t i = 0; i < molecule.atomCount(); ++i) {
1588 formalCharges.push_back(molecule.formalCharge(i));
1589 if (molecule.formalCharge(i) != 0)
1590 hasFormalCharges = true;
1591 }
1592 if (hasFormalCharges)
1593 atoms["formalCharges"] = formalCharges;
1594
1595 // isotopes (if present)
1596 json isotopes;
1597 const auto isotopeList = molecule.isotopes();
1598 if (isotopeList.size() == molecule.atomCount()) {
1599 for (Index i = 0; i < molecule.atomCount(); ++i) {
1600 isotopes.push_back(isotopeList[i]);
1601 }
1602 atoms["isotopes"] = isotopes;
1603 }
1604
1605 auto layer = LayerManager::getMoleculeInfo(&molecule)->layer;
1606 if (layer.atomCount() && molecule.atomCount()) {
1607 json atomLayer;
1608 // Use molecule atom count to avoid writing stale layer data
1609 for (Index i = 0; i < molecule.atomCount(); ++i) {
1610 atomLayer.push_back(layer.getLayerID(i));
1611 }
1612 atoms["layer"] = atomLayer;
1613 }
1614
1615 // TODO check for atom properties
1616 root["atoms"] = atoms; // end atoms
1617 }
1618
1619 // Create and populate the bond arrays.
1620 if (molecule.bondCount()) {
1621 json bonds;
1622 json connections;
1623 json order;
1624 for (Index i = 0; i < molecule.bondCount(); ++i) {
1625 Bond bond = molecule.bond(i);
1626 connections.push_back(bond.atom1().index());
1627 connections.push_back(bond.atom2().index());
1628 order.push_back(bond.order());
1629 }
1630 bonds["connections"]["index"] = connections;
1631 bonds["order"] = order;
1632
1633 // check if there are bond labels
1634 Array bondLabels = molecule.bondLabels();
1635 if (bondLabels.size() == molecule.bondCount()) {
1636 json labels;
1637 for (Index i = 0; i < molecule.bondCount(); ++i) {
1638 labels.push_back(bondLabels[i]);
1639 }
1640 bonds["labels"] = labels;
1641 }
1642
1643 // TODO check for bond properties
1644 root["bonds"] = bonds;
1645 }
1646
1647 // Create and populate any residue arrays
1648 if (molecule.residues().size() > 0) {
1649 json residues; // array of objects
1650 Array residueLabels = molecule.residueLabels();
1651 for (auto residue : molecule.residues()) {
1652 json entry;
1653 entry["name"] = residue.residueName();
1654 entry["id"] = residue.residueId();
1655 entry["chainId"] = residue.chainId();
1656 entry["secStruct"] = residue.secondaryStructure();
1657 if (residue.isHeterogen())
1658 entry["hetero"] = true;
1659
1660 json color;
1661 color.push_back(residue.color()[0]);
1662 color.push_back(residue.color()[1]);
1663 color.push_back(residue.color()[2]);
1664 entry["color"] = color;
1665
1666 json atoms;
1667 for (const auto& item : residue.atomNameMap()) {
1668 // dictionary between names and atom Id
1669 atoms[item.first] = item.second.index();
1670 }
1671 entry["atoms"] = atoms;
1672 residues.push_back(entry);
1673
1674 // do we have custom residue labels?
1675 if (residueLabels.size() > residue.residueId() + 1) {
1676 entry["label"] = residueLabels[residue.residueId()];
1677 }
1678 }
1679 root["residues"] = residues;
1680
1681 // TODO check for residue properties
1682 }
1683
1684 // any constraints?
1685 auto constraintList = molecule.constraints();
1686 if (!constraintList.empty()) {
1687 json constraints;
1688 for (auto& constraint : constraintList) {
1689 json constraintEntry;
1690 constraintEntry.push_back(constraint.value());
1691 constraintEntry.push_back(constraint.aIndex());
1692 constraintEntry.push_back(constraint.bIndex());
1693 if (constraint.cIndex() != MaxIndex) {
1694 constraintEntry.push_back(constraint.cIndex());
1695 }
1696 if (constraint.dIndex() != MaxIndex) {
1697 constraintEntry.push_back(constraint.dIndex());
1698 }
1699 constraints.push_back(constraintEntry);
1700 }
1701 root["constraints"] = constraints;
1702 }
1703
1704 // If there is vibrational data write this out too.
1705 if (molecule.vibrationFrequencies().size() > 0 &&
1706 (molecule.vibrationFrequencies().size() ==
1707 molecule.vibrationIRIntensities().size())) {
1708 json vibrations;
1709 json modes;
1710 json freqs;
1711 json inten;
1712 json raman;
1713 json eigenVectors;
1714 for (size_t i = 0; i < molecule.vibrationFrequencies().size(); ++i) {
1715 modes.push_back(static_cast<unsigned int>(i) + 1);
1716 freqs.push_back(molecule.vibrationFrequencies()[i]);
1717 inten.push_back(molecule.vibrationIRIntensities()[i]);
1718 if (molecule.vibrationRamanIntensities().size() > i)
1719 raman.push_back(molecule.vibrationRamanIntensities()[i]);
1720 Core::Array<Vector3> atomDisplacements = molecule.vibrationLx(i);
1721 json eigenVector;
1722 for (auto pos : atomDisplacements) {
1723 eigenVector.push_back(pos[0]);
1724 eigenVector.push_back(pos[1]);
1725 eigenVector.push_back(pos[2]);
1726 }
1727 eigenVectors.push_back(eigenVector);
1728 }
1729 vibrations["modes"] = modes;
1730 vibrations["frequencies"] = freqs;
1731 vibrations["intensities"] = inten;
1732 if (molecule.vibrationRamanIntensities().size() > 0)
1733 vibrations["ramanIntensities"] = raman;
1734 vibrations["eigenVectors"] = eigenVectors;
1735 root["vibrations"] = vibrations;
1736 }
1737
1738 auto names = LayerManager::getMoleculeInfo(&molecule);
1739 json layer;
1740 json visible;
1741 for (const bool v : names->visible) {
1742 visible.push_back(v);
1743 }
1744 layer["visible"] = visible;
1745 json locked;
1746 for (const bool l : names->locked) {
1747 locked.push_back(l);
1748 }
1749 layer["locked"] = locked;
1750 for (const auto& enables : names->enable) {
1751 json enable;
1752 for (const bool e : enables.second) {
1753 enable.push_back(e);
1754 }
1755 layer["enable"][enables.first] = enable;
1756 }
1757
1758 for (const auto& settings : names->settings) {
1759 json setting;
1760 for (const auto& e : settings.second) {
1761 setting.push_back(e->serialize());
1762 }
1763 layer["settings"][settings.first] = setting;
1764 }
1765 root["layer"] = layer;
1766
1767 if (isJson)
1768 #ifndef NDEBUG
1769 // if debugging, pretty print
1770 file << std::setw(2) << root;
1771 #else
1772 // release mode
1773 file << root;
1774 #endif
1775 else { // write msgpack
1776 json::to_msgpack(root, file);
1777 }
1778
1779 return true;
1780 }
1781
1782 vector<std::string> CjsonFormat::fileExtensions() const
1783 {
1784 vector<std::string> ext;
1785 ext.emplace_back("cjson");
1786 return ext;
1787 }
1788
1789 vector<std::string> CjsonFormat::mimeTypes() const
1790 {
1791 vector<std::string> mime;
1792 mime.emplace_back("chemical/x-cjson");
1793 return mime;
1794 }
1795
1796 } // namespace Avogadro::Io