-
-
Notifications
You must be signed in to change notification settings - Fork 186
/
Copy pathcjsonformat.cpp
1355 lines (1244 loc) · 46.6 KB
/
cjsonformat.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
This source file is part of the Avogadro project.
This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/
#include "cjsonformat.h"
#include <avogadro/core/crystaltools.h>
#include <avogadro/core/cube.h>
#include <avogadro/core/elements.h>
#include <avogadro/core/gaussianset.h>
#include <avogadro/core/layermanager.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/residue.h>
#include <avogadro/core/spacegroups.h>
#include <avogadro/core/unitcell.h>
#include <avogadro/core/utilities.h>
#include <nlohmann/json.hpp>
#include <iomanip>
#include <iostream>
using json = nlohmann::json;
namespace Avogadro::Io {
using std::string;
using std::vector;
using Core::Array;
using Core::Atom;
using Core::BasisSet;
using Core::Bond;
using Core::CrystalTools;
using Core::Cube;
using Core::GaussianSet;
using Core::LayerData;
using Core::LayerManager;
using Core::Molecule;
using Core::Residue;
using Core::Variant;
bool setJsonKey(json& j, Molecule& m, const std::string& key)
{
if (j.count(key) && j.find(key)->is_string()) {
m.setData(key, j.value(key, "undefined"));
return true;
}
return false;
}
bool isNumericArray(json& j)
{
if (j.is_array() && j.size() > 0) {
for (const auto& v : j) {
if (!v.is_number()) {
return false;
}
}
return true;
}
return false;
}
bool isBooleanArray(json& j)
{
if (j.is_array() && j.size() > 0) {
for (const auto& v : j) {
if (!v.is_boolean()) {
return false;
}
}
return true;
}
return false;
}
json eigenColToJson(const MatrixX& matrix, int column)
{
json j;
j = json::array();
for (Index i = 0; i < matrix.rows(); ++i) {
j.push_back(matrix(i, column));
}
return j;
}
bool CjsonFormat::read(std::istream& file, Molecule& molecule)
{
return deserialize(file, molecule, true);
}
bool CjsonFormat::deserialize(std::istream& file, Molecule& molecule,
bool isJson)
{
json jsonRoot;
// could throw parse errors
try {
if (isJson)
jsonRoot = json::parse(file, nullptr, false);
else // msgpack
jsonRoot = json::from_msgpack(file);
} catch (json::parse_error& e) {
appendError("Error reading CJSON file: " + string(e.what()));
return false;
} catch (json::type_error& e) {
appendError("Error reading CJSON file: " + string(e.what()));
return false;
}
if (jsonRoot.is_discarded()) {
appendError("Error reading CJSON file.");
return false;
}
if (!jsonRoot.is_object()) {
appendError("Error: Input is not a JSON object.");
return false;
}
auto jsonValue = jsonRoot.find("chemicalJson");
if (jsonValue == jsonRoot.end())
jsonValue = jsonRoot.find("chemical json");
if (jsonValue == jsonRoot.end()) {
appendError("Error: no \"chemical json\" key found.");
return false;
}
if (*jsonValue != 0 && *jsonValue != 1) {
appendError("Warning: chemical json version is not 0 or 1.");
return false;
}
// Read some basic key-value pairs (all strings).
setJsonKey(jsonRoot, molecule, "name");
setJsonKey(jsonRoot, molecule, "inchi");
setJsonKey(jsonRoot, molecule, "formula");
// Read in the atoms.
json atoms = jsonRoot["atoms"];
if (!atoms.is_object()) {
appendError("The 'atoms' key does not contain an object.");
return false;
}
if (!atoms.contains("elements")) {
appendError("The 'atoms' key does not contain an 'elements' key.");
return false;
}
if (atoms.contains("elements") && !atoms["elements"].is_object()) {
appendError("The 'elements' key does not contain an object.");
return false;
}
json elements = atoms["elements"];
if (!elements.contains("number")) {
appendError("The 'elements' key does not contain a 'number' key.");
return false;
}
json atomicNumbers = elements["number"];
// This represents our minimal spec for a molecule - atoms that have an
// atomic number.
if (isNumericArray(atomicNumbers) && atomicNumbers.size() > 0) {
for (auto& atomicNumber : atomicNumbers) {
if (!atomicNumber.is_number_integer() || atomicNumber < 0 ||
atomicNumber > Core::element_count) {
appendError("Error: atomic number is invalid.");
return false;
}
molecule.addAtom(atomicNumber);
}
} else {
// we're done, actually - this is an empty file
return true;
}
Index atomCount = molecule.atomCount();
if (atoms.contains("coords") && atoms["coords"].is_object()) {
if (atoms["coords"].contains("3d") && atoms["coords"]["3d"].is_array()) {
json atomicCoords = atoms["coords"]["3d"];
if (isNumericArray(atomicCoords) &&
atomicCoords.size() == 3 * atomCount) {
for (Index i = 0; i < atomCount; ++i) {
auto a = molecule.atom(i);
a.setPosition3d(Vector3(atomicCoords[3 * i], atomicCoords[3 * i + 1],
atomicCoords[3 * i + 2]));
}
}
}
if (atoms["coords"].contains("3dSets")) {
// Check for coordinate sets, and read them in if found, e.g.
// trajectories.
json coordSets = atoms["coords"]["3dSets"];
if (coordSets.is_array() && coordSets.size()) {
for (unsigned int i = 0; i < coordSets.size(); ++i) {
Array<Vector3> setArray;
json set = coordSets[i];
if (isNumericArray(set)) {
for (unsigned int j = 0; j < set.size() / 3; ++j) {
setArray.push_back(
Vector3(set[3 * j], set[3 * j + 1], set[3 * j + 2]));
}
molecule.setCoordinate3d(setArray, i);
}
}
// Make sure the first step is active once we are done loading the sets.
molecule.setCoordinate3d(0);
}
}
}
// Array of vector3 for forces if available
if (atoms.contains("forces")) {
json forces = atoms["forces"];
if (isNumericArray(forces) && forces.size() == 3 * atomCount) {
for (Index i = 0; i < atomCount; ++i) {
auto a = molecule.atom(i);
a.setForceVector(
Vector3(forces[3 * i], forces[3 * i + 1], forces[3 * i + 2]));
}
}
}
// labels
if (atoms.contains("labels")) {
json labels = atoms["labels"];
if (labels.is_array() && labels.size() == atomCount) {
for (size_t i = 0; i < atomCount; ++i) {
molecule.setAtomLabel(i, labels[i]);
}
}
}
// formal charges
if (atoms.contains("formalCharges")) {
json formalCharges = atoms["formalCharges"];
if (formalCharges.is_array() && formalCharges.size() == atomCount) {
for (size_t i = 0; i < atomCount; ++i) {
molecule.atom(i).setFormalCharge(formalCharges[i]);
}
}
}
// Read in colors if they are present.
if (atoms.contains("colors")) {
json colors = atoms["colors"];
if (colors.is_array() && colors.size() == 3 * atomCount) {
for (Index i = 0; i < atomCount; ++i) {
Vector3ub color(colors[3 * i], colors[3 * i + 1], colors[3 * i + 2]);
molecule.setColor(i, color);
}
}
}
// Selection is optional, but if present should be loaded.
if (atoms.contains("selected")) {
json selection = atoms["selected"];
if (isBooleanArray(selection) && selection.size() == atomCount)
for (Index i = 0; i < atomCount; ++i)
molecule.setAtomSelected(i, selection[i]);
else if (isNumericArray(selection) && selection.size() == atomCount)
for (Index i = 0; i < atomCount; ++i)
molecule.setAtomSelected(i, selection[i] != 0);
if (atoms.find("layer") != atoms.end()) {
json layerJson = atoms["layer"];
if (isNumericArray(layerJson)) {
auto& layer = LayerManager::getMoleculeInfo(&molecule)->layer;
for (Index i = 0; i < atomCount && i < layerJson.size(); ++i) {
while (layerJson[i] > layer.maxLayer()) {
layer.addLayer();
}
layer.addAtom(layerJson[i], i);
}
}
}
}
// Bonds are optional, but if present should be loaded.
if (jsonRoot.contains("bonds")) {
json bonds = jsonRoot["bonds"];
if (bonds.is_object() && isNumericArray(bonds["connections"]["index"])) {
json connections = bonds["connections"]["index"];
for (unsigned int i = 0; i < connections.size() / 2; ++i) {
molecule.addBond(static_cast<Index>(connections[2 * i]),
static_cast<Index>(connections[2 * i + 1]), 1);
}
if (bonds.contains("order")) {
json order = bonds["order"];
if (isNumericArray(order)) {
for (unsigned int i = 0; i < molecule.bondCount() && i < order.size();
++i) {
molecule.bond(i).setOrder(static_cast<int>(order[i]));
}
}
}
// are there bond labels?
if (bonds.contains("labels")) {
json bondLabels = bonds["labels"];
if (bondLabels.is_array()) {
for (unsigned int i = 0;
i < molecule.bondCount() && i < bondLabels.size(); ++i) {
molecule.setBondLabel(i, bondLabels[i]);
}
}
}
}
}
// residues are optional, but should be loaded
if (jsonRoot.contains("residues")) {
json residues = jsonRoot["residues"];
if (residues.is_array()) {
for (auto residue : residues) {
if (!residue.is_object())
continue; // malformed
auto name = residue["name"].get<std::string>();
auto id = static_cast<Index>(residue["id"]);
auto chainId = residue["chainId"].get<char>();
Residue newResidue(name, id, chainId);
json hetero = residue["hetero"];
if (hetero == true)
newResidue.setHeterogen(true);
int secStruct = residue.value("secStruct", -1);
if (secStruct != -1)
newResidue.setSecondaryStructure(
static_cast<Avogadro::Core::Residue::SecondaryStructure>(
secStruct));
json atomsResidue = residue["atoms"];
if (atomsResidue.is_object()) {
for (auto& item : atomsResidue.items()) {
if (item.value() < molecule.atomCount()) {
const Atom& atom = molecule.atom(item.value());
newResidue.addResidueAtom(item.key(), atom);
}
}
}
json color = residue["color"];
if (color.is_array() && color.size() == 3) {
Vector3ub col = Vector3ub(color[0], color[1], color[2]);
newResidue.setColor(col);
}
molecule.addResidue(newResidue);
}
}
}
if (jsonRoot.contains("unitCell") || jsonRoot.contains("unit cell")) {
json unitCell = jsonRoot["unitCell"];
if (!unitCell.is_object())
unitCell = jsonRoot["unit cell"];
if (unitCell.is_object()) {
Core::UnitCell* unitCellObject = nullptr;
// read in cell vectors in preference to a, b, c parameters
json cellVectors = unitCell["cellVectors"];
if (cellVectors.is_array() && cellVectors.size() == 9 &&
isNumericArray(cellVectors)) {
Vector3 aVector(cellVectors[0], cellVectors[1], cellVectors[2]);
Vector3 bVector(cellVectors[3], cellVectors[4], cellVectors[5]);
Vector3 cVector(cellVectors[6], cellVectors[7], cellVectors[8]);
unitCellObject = new Core::UnitCell(aVector, bVector, cVector);
} else if (unitCell["a"].is_number() && unitCell["b"].is_number() &&
unitCell["c"].is_number() && unitCell["alpha"].is_number() &&
unitCell["beta"].is_number() &&
unitCell["gamma"].is_number()) {
Real a = static_cast<Real>(unitCell["a"]);
Real b = static_cast<Real>(unitCell["b"]);
Real c = static_cast<Real>(unitCell["c"]);
Real alpha = static_cast<Real>(unitCell["alpha"]) * DEG_TO_RAD;
Real beta = static_cast<Real>(unitCell["beta"]) * DEG_TO_RAD;
Real gamma = static_cast<Real>(unitCell["gamma"]) * DEG_TO_RAD;
unitCellObject = new Core::UnitCell(a, b, c, alpha, beta, gamma);
}
if (unitCellObject != nullptr)
molecule.setUnitCell(unitCellObject);
// check for Hall number if present
if (unitCell["hallNumber"].is_number()) {
auto hallNumber = static_cast<int>(unitCell["hallNumber"]);
if (hallNumber > 0 && hallNumber < 531)
molecule.setHallNumber(hallNumber);
} else if (unitCell["spaceGroup"].is_string()) {
auto hallNumber = Core::SpaceGroups::hallNumber(unitCell["spaceGroup"]);
if (hallNumber != 0)
molecule.setHallNumber(hallNumber);
}
}
}
if (atoms["coords"].contains("3dFractional") ||
atoms["coords"].contains("3d fractional")) {
json fractional = atoms["coords"]["3dFractional"];
if (!fractional.is_array())
fractional = atoms["coords"]["3d fractional"];
if (fractional.is_array() && fractional.size() == 3 * atomCount &&
isNumericArray(fractional) && molecule.unitCell()) {
Array<Vector3> fcoords;
fcoords.reserve(atomCount);
for (Index i = 0; i < atomCount; ++i) {
fcoords.push_back(Vector3(static_cast<Real>(fractional[i * 3 + 0]),
static_cast<Real>(fractional[i * 3 + 1]),
static_cast<Real>(fractional[i * 3 + 2])));
}
CrystalTools::setFractionalCoordinates(molecule, fcoords);
}
}
// Basis set is optional, if present read it in.
if (jsonRoot.contains("basisSet")) {
json basisSet = jsonRoot["basisSet"];
if (basisSet.is_object()) {
auto* basis = new GaussianSet;
basis->setMolecule(&molecule);
// Gather the relevant pieces together so that they can be read in.
json shellTypes = basisSet["shellTypes"];
json primitivesPerShell = basisSet["primitivesPerShell"];
json shellToAtomMap = basisSet["shellToAtomMap"];
json exponents = basisSet["exponents"];
json coefficients = basisSet["coefficients"];
int nGTO = 0;
for (unsigned int i = 0; i < shellTypes.size(); ++i) {
GaussianSet::orbital type;
switch (static_cast<int>(shellTypes[i])) {
case 0:
type = GaussianSet::S;
break;
case 1:
type = GaussianSet::P;
break;
case 2:
type = GaussianSet::D;
break;
case -2:
type = GaussianSet::D5;
break;
default:
// If we encounter GTOs we do not understand, the basis is likely
// invalid
type = GaussianSet::UU;
}
if (type != GaussianSet::UU) {
int b = basis->addBasis(static_cast<int>(shellToAtomMap[i]), type);
for (int j = 0; j < static_cast<int>(primitivesPerShell[i]); ++j) {
basis->addGto(b, coefficients[nGTO], exponents[nGTO]);
++nGTO;
}
}
}
json orbitals = jsonRoot["orbitals"];
if (orbitals.is_object() && basis->isValid()) {
basis->setElectronCount(orbitals["electronCount"]);
json occupations = orbitals["occupations"];
if (isNumericArray(occupations)) {
std::vector<unsigned char> occs;
for (auto& occupation : occupations)
occs.push_back(static_cast<unsigned char>(occupation));
basis->setMolecularOrbitalOccupancy(occupations);
}
json energies = orbitals["energies"];
if (isNumericArray(energies)) {
std::vector<double> energyArray;
for (auto& energie : energies)
energyArray.push_back(static_cast<double>(energie));
basis->setMolecularOrbitalEnergy(energyArray);
}
json numbers = orbitals["numbers"];
if (isNumericArray(numbers)) {
std::vector<unsigned int> numArray;
for (auto& number : numbers)
numArray.push_back(static_cast<unsigned int>(number));
basis->setMolecularOrbitalNumber(numArray);
}
json symmetryLabels = orbitals["symmetries"];
if (symmetryLabels.is_array()) {
std::vector<std::string> symArray;
for (auto& sym : symmetryLabels)
symArray.push_back(sym);
basis->setSymmetryLabels(symArray);
}
json moCoefficients = orbitals["moCoefficients"];
json moCoefficientsA = orbitals["alphaCoefficients"];
json moCoefficientsB = orbitals["betaCoefficients"];
bool openShell = false;
if (isNumericArray(moCoefficients)) {
std::vector<double> coeffs;
for (auto& moCoefficient : moCoefficients)
coeffs.push_back(static_cast<double>(moCoefficient));
basis->setMolecularOrbitals(coeffs);
} else if (isNumericArray(moCoefficientsA) &&
isNumericArray(moCoefficientsB)) {
std::vector<double> coeffsA;
for (auto& i : moCoefficientsA)
coeffsA.push_back(static_cast<double>(i));
std::vector<double> coeffsB;
for (auto& i : moCoefficientsB)
coeffsB.push_back(static_cast<double>(i));
basis->setMolecularOrbitals(coeffsA, BasisSet::Alpha);
basis->setMolecularOrbitals(coeffsB, BasisSet::Beta);
openShell = true;
} else {
std::cout << "No orbital cofficients found!" << std::endl;
}
// Check for orbital coefficient sets, these are paired with coordinates
// when they exist, but have constant basis set, atom types, etc.
if (orbitals["sets"].is_array() && orbitals["sets"].size()) {
json orbSets = orbitals["sets"];
for (unsigned int idx = 0; idx < orbSets.size(); ++idx) {
moCoefficients = orbSets[idx]["moCoefficients"];
moCoefficientsA = orbSets[idx]["alphaCoefficients"];
moCoefficientsB = orbSets[idx]["betaCoefficients"];
if (isNumericArray(moCoefficients)) {
std::vector<double> coeffs;
for (auto& moCoefficient : moCoefficients)
coeffs.push_back(static_cast<double>(moCoefficient));
basis->setMolecularOrbitals(coeffs, BasisSet::Paired, idx);
} else if (isNumericArray(moCoefficientsA) &&
isNumericArray(moCoefficientsB)) {
std::vector<double> coeffsA;
for (auto& i : moCoefficientsA)
coeffsA.push_back(static_cast<double>(i));
std::vector<double> coeffsB;
for (auto& i : moCoefficientsB)
coeffsB.push_back(static_cast<double>(i));
basis->setMolecularOrbitals(coeffsA, BasisSet::Alpha, idx);
basis->setMolecularOrbitals(coeffsB, BasisSet::Beta, idx);
openShell = true;
}
}
// Set the first step as active.
basis->setActiveSetStep(0);
}
if (openShell) {
// look for alpha and beta orbital energies
json energiesA = orbitals["alphaEnergies"];
json energiesB = orbitals["betaEnergies"];
// check if they are numeric arrays
if (isNumericArray(energiesA) && isNumericArray(energiesB)) {
std::vector<double> moEnergiesA;
for (auto& i : energiesA)
moEnergiesA.push_back(static_cast<double>(i));
std::vector<double> moEnergiesB;
for (auto& i : energiesB)
moEnergiesB.push_back(static_cast<double>(i));
basis->setMolecularOrbitalEnergy(moEnergiesA, BasisSet::Alpha);
basis->setMolecularOrbitalEnergy(moEnergiesB, BasisSet::Beta);
// look for alpha and beta orbital occupations
json occupationsA = orbitals["alphaOccupations"];
json occupationsB = orbitals["betaOccupations"];
// check if they are numeric arrays
if (isNumericArray(occupationsA) && isNumericArray(occupationsB)) {
std::vector<unsigned char> moOccupationsA;
for (auto& i : occupationsA)
moOccupationsA.push_back(static_cast<unsigned char>(i));
std::vector<unsigned char> moOccupationsB;
for (auto& i : occupationsB)
moOccupationsB.push_back(static_cast<unsigned char>(i));
basis->setMolecularOrbitalOccupancy(moOccupationsA,
BasisSet::Alpha);
basis->setMolecularOrbitalOccupancy(moOccupationsB,
BasisSet::Beta);
}
}
}
}
molecule.setBasisSet(basis);
}
}
// See if there is any vibration data, load it if so.
json vibrations = jsonRoot["vibrations"];
if (vibrations.is_object()) {
json frequencies = vibrations["frequencies"];
if (isNumericArray(frequencies)) {
Array<double> freqs;
for (auto& frequencie : frequencies) {
freqs.push_back(static_cast<double>(frequencie));
}
molecule.setVibrationFrequencies(freqs);
}
json intensities = vibrations["intensities"];
if (isNumericArray(intensities)) {
Array<double> intens;
for (auto& intensitie : intensities) {
intens.push_back(static_cast<double>(intensitie));
}
molecule.setVibrationIRIntensities(intens);
}
json raman = vibrations["ramanIntensities"];
if (isNumericArray(raman)) {
Array<double> intens;
for (auto& i : raman) {
intens.push_back(static_cast<double>(i));
}
molecule.setVibrationRamanIntensities(intens);
}
json displacements = vibrations["eigenVectors"];
if (displacements.is_array()) {
Array<Array<Vector3>> disps;
for (auto arr : displacements) {
if (isNumericArray(arr)) {
Array<Vector3> mode;
mode.resize(arr.size() / 3);
double* ptr = &mode[0][0];
for (auto& j : arr) {
*(ptr++) = static_cast<double>(j);
}
disps.push_back(mode);
}
}
molecule.setVibrationLx(disps);
}
}
// check for spectra data
json spectra = jsonRoot["spectra"];
if (spectra.is_object()) {
// electronic
json electronic = spectra["electronic"];
if (electronic.is_object()) {
// check to see "energies" and "intensities"
json energies = electronic["energies"];
json intensities = electronic["intensities"];
// make sure they are both numeric arrays
if (isNumericArray(energies) && isNumericArray(intensities)) {
// make sure they are the same size
if (energies.size() == intensities.size()) {
// create the matrix
MatrixX electronicData(energies.size(), 2);
// copy the data
for (std::size_t i = 0; i < energies.size(); ++i) {
electronicData(i, 0) = energies[i];
electronicData(i, 1) = intensities[i];
}
// set the data
molecule.setSpectra("Electronic", electronicData);
}
}
// check if there's CD data for "rotation"
json rotation = electronic["rotation"];
if (isNumericArray(rotation) && rotation.size() == energies.size()) {
MatrixX rotationData(rotation.size(), 2);
for (std::size_t i = 0; i < rotation.size(); ++i) {
rotationData(i, 0) = energies[i];
rotationData(i, 1) = rotation[i];
}
molecule.setSpectra("CircularDichroism", rotationData);
}
}
// nmr
json nmr = spectra["nmr"];
if (nmr.is_object()) {
// chemical shifts
json chemicalShifts = nmr["shifts"];
if (isNumericArray(chemicalShifts)) {
MatrixX chemicalShiftData(chemicalShifts.size(), 2);
for (std::size_t i = 0; i < chemicalShifts.size(); ++i) {
chemicalShiftData(i, 0) = static_cast<double>(chemicalShifts[i]);
chemicalShiftData(i, 1) = 1.0;
}
molecule.setSpectra("NMR", chemicalShiftData);
}
}
}
// properties
if (jsonRoot.find("properties") != jsonRoot.end()) {
json properties = jsonRoot["properties"];
if (properties.is_object()) {
if (properties.find("totalCharge") != properties.end()) {
molecule.setData("totalCharge",
static_cast<int>(properties["totalCharge"]));
} else if (properties.find("totalSpinMultiplicity") != properties.end()) {
molecule.setData("totalSpinMultiplicity",
static_cast<int>(properties["totalSpinMultiplicity"]));
} else if (properties.find("dipoleMoment") != properties.end()) {
// read the numeric array
json dipole = properties["dipoleMoment"];
if (isNumericArray(dipole) && dipole.size() == 3) {
Core::Variant dipoleMoment(dipole[0], dipole[1], dipole[2]);
molecule.setData("dipoleMoment", dipoleMoment);
}
}
// iterate through everything else
for (auto& element : properties.items()) {
if (element.key() == "totalCharge" ||
element.key() == "totalSpinMultiplicity" ||
element.key() == "dipoleMoment") {
continue;
}
if (element.value().type() == json::value_t::array) {
// check if it is a numeric array to go into Eigen::MatrixXd
json j = element.value(); // convenience
std::size_t rows = j.size();
MatrixX matrix;
matrix.resize(rows, 1); // default to 1 columns
bool isNumeric = true;
for (std::size_t row = 0; row < j.size(); ++row) {
const auto& jrow = j.at(row);
// check to see if we have a simple vector or a matrix
if (jrow.type() == json::value_t::array) {
matrix.conservativeResize(rows, jrow.size());
for (std::size_t col = 0; col < jrow.size(); ++col) {
const auto& value = jrow.at(col);
if (value.type() == json::value_t::number_float ||
value.type() == json::value_t::number_integer ||
value.type() == json::value_t::number_unsigned)
matrix(row, col) = value.get<double>();
else {
isNumeric = false;
break;
}
}
} else if (jrow.type() == json::value_t::number_float ||
jrow.type() == json::value_t::number_integer ||
jrow.type() == json::value_t::number_unsigned) {
// just a row vector
matrix(row, 0) = jrow.get<double>();
} else {
isNumeric = false;
break;
}
}
if (isNumeric)
molecule.setData(element.key(), matrix);
// TODO: add support for non-numeric arrays
// std::cout << " property: " << element.key() << " = " << matrix
// << " size " << matrix.rows() << 'x' << matrix.cols()
// << std::endl;
} else if (element.value().type() == json::value_t::number_float) {
molecule.setData(element.key(), element.value().get<double>());
} else if (element.value().type() == json::value_t::number_integer) {
molecule.setData(element.key(), element.value().get<int>());
} else if (element.value().type() == json::value_t::boolean) {
molecule.setData(element.key(), element.value().get<bool>());
} else if (element.value().type() == json::value_t::string) {
molecule.setData(element.key(), element.value().get<std::string>());
} else {
std::cout << " cannot store property: " << element.key() << " = "
<< element.value() << " type "
<< element.value().type_name() << std::endl;
}
}
}
}
// inputParameters are calculation metadata
if (jsonRoot.find("inputParameters") != jsonRoot.end()) {
json inputParameters = jsonRoot["inputParameters"];
// add this as a string to the molecule data
molecule.setData("inputParameters", inputParameters.dump());
}
// Partial charges are optional, but if present should be loaded.
if (atoms.contains("partialCharges")) {
json partialCharges = atoms["partialCharges"];
if (partialCharges.is_object()) {
// keys are types, values are arrays of charges
for (auto& kv : partialCharges.items()) {
MatrixX charges(atomCount, 1);
if (isNumericArray(kv.value()) && kv.value().size() == atomCount) {
for (size_t i = 0; i < kv.value().size(); ++i) {
charges(i, 0) = kv.value()[i];
}
molecule.setPartialCharges(kv.key(), charges);
}
}
}
}
if (jsonRoot.find("layer") != jsonRoot.end()) {
auto names = LayerManager::getMoleculeInfo(&molecule);
json visible = jsonRoot["layer"]["visible"];
if (isBooleanArray(visible)) {
for (const auto& v : visible) {
names->visible.push_back(v);
}
}
json locked = jsonRoot["layer"]["locked"];
if (isBooleanArray(locked)) {
for (const auto& l : locked) {
names->locked.push_back(l);
}
}
json enables = jsonRoot["layer"]["enable"];
for (const auto& enable : enables.items()) {
names->enable[enable.key()] = std::vector<bool>();
for (const auto& e : enable.value()) {
names->enable[enable.key()].push_back(e);
}
}
json settings = jsonRoot["layer"]["settings"];
for (const auto& setting : settings.items()) {
names->settings[setting.key()] = Core::Array<LayerData*>();
for (const auto& s : setting.value()) {
names->settings[setting.key()].push_back(new LayerData(s));
}
}
}
return true;
}
bool CjsonFormat::write(std::ostream& file, const Molecule& molecule)
{
return serialize(file, molecule, true);
}
bool CjsonFormat::serialize(std::ostream& file, const Molecule& molecule,
bool isJson)
{
json opts;
if (!options().empty())
opts = json::parse(options(), nullptr, false);
else
opts = json::object();
json root;
root["chemicalJson"] = 1;
if (opts.value("properties", true)) {
if (molecule.data("name").type() == Variant::String)
root["name"] = molecule.data("name").toString().c_str();
if (molecule.data("inchi").type() == Variant::String)
root["inchi"] = molecule.data("inchi").toString().c_str();
}
json properties;
// these methods assume neutral singlet if not set
// or approximate from formal charges and # of electrons
properties["totalCharge"] = molecule.totalCharge();
properties["totalSpinMultiplicity"] = molecule.totalSpinMultiplicity();
// loop through all other properties
const auto map = molecule.dataMap();
for (const auto& element : map) {
if (element.first == "name" || element.first == "inchi")
continue;
// check for "inputParameters" and handle it separately
if (element.first == "inputParameters") {
json inputParameters = json::parse(element.second.toString());
root["inputParameters"] = inputParameters;
continue;
}
if (element.second.type() == Variant::String)
properties[element.first] = element.second.toString().c_str();
else if (element.second.type() == Variant::Double)
properties[element.first] = element.second.toDouble();
else if (element.second.type() == Variant::Float)
properties[element.first] = element.second.toFloat();
else if (element.second.type() == Variant::Int)
properties[element.first] = element.second.toInt();
else if (element.second.type() == Variant::Bool)
properties[element.first] = element.second.toBool();
else if (element.second.type() == Variant::Vector) {
// e.g. dipole moment
Vector3 v = element.second.toVector3();
json vector;
vector.push_back(v.x());
vector.push_back(v.y());
vector.push_back(v.z());
properties[element.first] = vector;
} else if (element.second.type() == Variant::Matrix) {
MatrixX m = element.second.toMatrix();
json matrix;
for (int i = 0; i < m.rows(); ++i) {
json row;
for (int j = 0; j < m.cols(); ++j) {
row.push_back(m(i, j));
}
matrix.push_back(row);
}
properties[element.first] = matrix;
}
}
root["properties"] = properties;
if (molecule.unitCell()) {
json unitCell;
unitCell["a"] = molecule.unitCell()->a();
unitCell["b"] = molecule.unitCell()->b();
unitCell["c"] = molecule.unitCell()->c();
unitCell["alpha"] = molecule.unitCell()->alpha() * RAD_TO_DEG;
unitCell["beta"] = molecule.unitCell()->beta() * RAD_TO_DEG;
unitCell["gamma"] = molecule.unitCell()->gamma() * RAD_TO_DEG;
json vectors;
vectors.push_back(molecule.unitCell()->aVector().x());
vectors.push_back(molecule.unitCell()->aVector().y());
vectors.push_back(molecule.unitCell()->aVector().z());
vectors.push_back(molecule.unitCell()->bVector().x());
vectors.push_back(molecule.unitCell()->bVector().y());
vectors.push_back(molecule.unitCell()->bVector().z());
vectors.push_back(molecule.unitCell()->cVector().x());
vectors.push_back(molecule.unitCell()->cVector().y());
vectors.push_back(molecule.unitCell()->cVector().z());
unitCell["cellVectors"] = vectors;
// write the Hall number and space group
unitCell["hallNumber"] = molecule.hallNumber();
unitCell["spaceGroup"] =
Core::SpaceGroups::international(molecule.hallNumber());
root["unitCell"] = unitCell;
}
// check for spectra data
// vibrations are separate
if (molecule.spectraTypes().size() != 0) {
json spectra, electronic, nmr;
bool hasElectronic = false;
for (const auto& type : molecule.spectraTypes()) {
if (type == "Electronic") {
hasElectronic = true;
electronic["energies"] = eigenColToJson(molecule.spectra(type), 0);
electronic["intensities"] = eigenColToJson(molecule.spectra(type), 1);
} else if (type == "CircularDichroism") {
electronic["rotation"] = eigenColToJson(molecule.spectra(type), 1);
} else if (type == "NMR") {
json data;
data["shifts"] = eigenColToJson(molecule.spectra(type), 0);
spectra["nmr"] = data;
}
}
if (hasElectronic) {
spectra["electronic"] = electronic;
}
root["spectra"] = spectra;
}
// Create a basis set/MO matrix we can round trip.
if (molecule.basisSet() &&
dynamic_cast<const GaussianSet*>(molecule.basisSet())) {
json basis;
auto gaussian = dynamic_cast<const GaussianSet*>(molecule.basisSet());
// Map the shell types from enumeration to integer values.
auto symmetry = gaussian->symmetry();
json shellTypes;
for (int i : symmetry) {
switch (i) {
case GaussianSet::S:
shellTypes.push_back(0);
break;
case GaussianSet::P:
shellTypes.push_back(1);
break;
case GaussianSet::D:
shellTypes.push_back(2);
break;
case GaussianSet::D5:
shellTypes.push_back(-2);
break;
default:
// Something bad, put in a silly number...
shellTypes.push_back(426942);
}
}
basis["shellTypes"] = shellTypes;
// This bit is slightly tricky, map from our index to primitives per
// shell.
if (gaussian->gtoIndices().size() && gaussian->atomIndices().size()) {
auto gtoIndices = gaussian->gtoIndices();
auto gtoA = gaussian->gtoA();
json primitivesPerShell;
for (size_t i = 0; i < gtoIndices.size() - 1; ++i)
primitivesPerShell.push_back(gtoIndices[i + 1] - gtoIndices[i]);
primitivesPerShell.push_back(gtoA.size() - gtoIndices.back());
basis["primitivesPerShell"] = primitivesPerShell;
auto atomIndices = gaussian->atomIndices();
json shellToAtomMap;
for (unsigned int& atomIndice : atomIndices)
shellToAtomMap.push_back(atomIndice);
basis["shellToAtomMap"] = shellToAtomMap;
auto gtoC = gaussian->gtoC();
json exponents;
json coefficients;