Debian Codegraph @

avogadro/quantumio/nwchemjson.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 "nwchemjson.h"
7
8 #include <avogadro/core/crystaltools.h>
9 #include <avogadro/core/elements.h>
10 #include <avogadro/core/gaussianset.h>
11 #include <avogadro/core/molecule.h>
12 #include <avogadro/core/unitcell.h>
13 #include <avogadro/core/utilities.h>
14
15 #include <nlohmann/json.hpp>
16
17 #include <iostream>
18
19 namespace Avogadro::QuantumIO {
20
21 using std::string;
22 using std::vector;
23
24 using nlohmann::json;
25
26 using Core::Array;
27 using Core::Atom;
28 using Core::GaussianSet;
29 using Core::Molecule;
30 using Core::split;
31
32 NWChemJson::NWChemJson() {}
33
34 NWChemJson::~NWChemJson() {}
35
36 bool NWChemJson::read(std::istream& file, Molecule& molecule)
37 {
38 json root;
39 try {
40 file >> root;
41 } catch (json::parse_error& e) {
42 appendError("Error parsing JSON: " + string(e.what()));
43 return false;
44 }
45
46 if (!root.is_object()) {
47 appendError("Error: Input is not a JSON object.");
48 return false;
49 }
50
51 if (root.find("simulation") == root.end()) {
52 appendError("Error: no \"simulation\" key found.");
53 return false;
54 }
55
56 json simulation = root["simulation"];
57
58 if (simulation.find("calculations") == simulation.end() ||
59 !simulation["calculations"].is_array()) {
60 appendError("Error: no \"calculations\" array found.");
61 return false;
62 }
63
64 // Scan the calculations array for calculationSetup.molecule objects.
65 json calculations = simulation["calculations"];
66
67 // Iterate through the objects in the array, and print out any molecules.
68 json moleculeArray = json::array();
69 json basisSetArray = json::array();
70 json calculationVib;
71 json molecularOrbitals;
72 int numberOfElectrons = 0;
73 string theory;
74 string xcFunctional;
75 for (const auto& calcObj : calculations) {
76 if (calcObj.is_object()) {
77 string calcType = calcObj.value("calculationType", "");
78 // Store the last vibrational frequencies calculation object.
79 if (calcType == "vibrationalModes")
80 calculationVib = calcObj;
81 json calcSetup = calcObj.value("calculationSetup", json());
82 json calcMol = calcSetup.value("molecule", json());
83 numberOfElectrons = calcSetup.value("numberOfElectrons", -1);
84 if (calcSetup.count("exchangeCorrelationFunctional") &&
85 calcSetup["exchangeCorrelationFunctional"].is_array() &&
86 !calcSetup["exchangeCorrelationFunctional"].empty()) {
87 json functional = calcSetup["exchangeCorrelationFunctional"][0];
88 if (functional.is_object()) {
89 xcFunctional = functional.value("xcName", "");
90 }
91 if (xcFunctional == "B3LYP Method XC Potential") {
92 xcFunctional = "b3lyp";
93 }
94 }
95 if (calcSetup.count("waveFunctionTheory")) {
96 theory = calcSetup["waveFunctionTheory"].get<std::string>();
97 if (theory == "Density Functional Theory") {
98 theory = "dft";
99 }
100 }
101 if (!calcMol.is_null() && calcMol.is_object())
102 moleculeArray.push_back(calcMol);
103 json basisSet = calcSetup.value("basisSet", json());
104 if (!basisSet.is_null() && basisSet.is_object())
105 basisSetArray.push_back(basisSet);
106
107 json calcResults = calcObj.value("calculationResults", json());
108 calcMol = calcResults.value("molecule", json());
109 if (!calcMol.is_null() && calcMol.is_object())
110 moleculeArray.push_back(calcMol);
111 // There is currently one id for all, just get the last one we find.
112 if (calcResults.count("molecularOrbitals") &&
113 calcResults["molecularOrbitals"].is_object()) {
114 molecularOrbitals = calcResults["molecularOrbitals"];
115 }
116 }
117 }
118
119 // For now, we are just grabbing the "last" molecule, and using that. This
120 // needs more complex logic to step through the file and do it properly.
121 json atoms;
122 if (!moleculeArray.empty()) {
123 json finalMol = moleculeArray.back();
124 atoms = finalMol.value("atoms", json());
125 }
126 if (atoms.is_array()) {
127 for (auto jsonAtom : atoms) {
128 if (jsonAtom.is_null() || !jsonAtom.is_object())
129 continue;
130 Atom a = molecule.addAtom(
131 static_cast<unsigned char>(jsonAtom.value("elementNumber", 0)));
132 json pos = jsonAtom["cartesianCoordinates"]["value"];
133 Vector3 position;
134 if (pos.is_array() && pos.size() >= 3)
135 position = Vector3(pos[0], pos[1], pos[2]);
136 string units = jsonAtom["cartesianCoordinates"]["units"];
137 if (units == "bohr")
138 position *= BOHR_TO_ANGSTROM_D;
139 a.setPosition3d(position);
140 }
141 }
142 // Perceive bonds for the molecule.
143 molecule.perceiveBondsSimple();
144 molecule.perceiveBondOrders();
145
146 // Add in the electronic structure information if available.
147 if (molecularOrbitals.is_object() &&
148 molecularOrbitals["atomicOrbitalDescriptions"].is_array()) {
149 json basisSet;
150 if (!basisSetArray.empty())
151 basisSet = basisSetArray.back();
152 json orbDesc = molecularOrbitals.value("atomicOrbitalDescriptions", json());
153
154 // Figure out the mapping of basis set to molecular orbitals.
155 Array<int> atomNumber;
156 Array<string> atomSymbol;
157 for (auto& i : orbDesc) {
158 string desc = i;
159 vector<string> parts = split(desc, ' ');
160 assert(parts.size() == 3);
161 int num = Core::lexicalCast<int>(parts[0]).value_or(0);
162 if (atomNumber.size() > 0 && atomNumber.back() == num)
163 continue;
164 atomNumber.push_back(num);
165 atomSymbol.push_back(parts[1]);
166 }
167
168 // Now create the structure, and expand out the orbitals.
169 auto* basis = new GaussianSet;
170 basis->setMolecule(&molecule);
171 string basisSetName;
172 for (size_t i = 0; i < atomSymbol.size(); ++i) {
173 string symbol = atomSymbol[i];
174 json basisFunctions = basisSet.value("basisFunctions", json());
175 json currentFunction;
176 for (auto& basisFunction : basisFunctions) {
177 currentFunction = basisFunction;
178
179 string elementType;
180 if (currentFunction.count("elementLabel"))
181 elementType = currentFunction["elementLabel"].get<std::string>();
182 else if (currentFunction.count("elementType"))
183 elementType = currentFunction["elementType"].get<std::string>();
184
185 if (elementType == symbol)
186 break;
187
188 currentFunction = json();
189 }
190
191 if (currentFunction.is_null())
192 break;
193
194 if (currentFunction.count("basisSetName")) {
195 if (basisSetName.empty()) {
196 basisSetName = currentFunction["basisSetName"].get<std::string>();
197 } else if (basisSetName != currentFunction["basisSetName"]) {
198 basisSetName = "Custom";
199 }
200 }
201
202 json contraction = currentFunction.value("basisSetContraction", json());
203 bool spherical =
204 currentFunction.value("basisSetHarmonicType", "") == "spherical";
205 for (auto contractionShell : contraction) {
206 string shellType;
207 if (contractionShell.count("basisSetShell"))
208 shellType = contractionShell["basisSetShell"].get<std::string>();
209 else if (contractionShell.count("basisSetShellType"))
210 shellType = contractionShell["basisSetShellType"].get<std::string>();
211 json exponent = contractionShell.value("basisSetExponent", json());
212 json coefficient =
213 contractionShell.value("basisSetCoefficient", json());
214 assert(exponent.size() == coefficient.size());
215 GaussianSet::orbital type = GaussianSet::UU;
216 if (shellType == "s")
217 type = GaussianSet::S;
218 else if (shellType == "p")
219 type = GaussianSet::P;
220 else if (shellType == "d" && spherical)
221 type = GaussianSet::D5;
222 else if (shellType == "d")
223 type = GaussianSet::D;
224 else if (shellType == "f" && spherical)
225 type = GaussianSet::F7;
226 else if (shellType == "f")
227 type = GaussianSet::F;
228
229 if (type != GaussianSet::UU) {
230 int b = basis->addBasis(i, type);
231 for (size_t k = 0; k < exponent.size() && k < coefficient.size();
232 ++k) {
233 basis->addGto(b, coefficient[k], exponent[k]);
234 }
235 }
236 }
237 }
238 // Now to add the molecular orbital coefficients.
239 json moCoeffs = molecularOrbitals.value("molecularOrbital", json());
240 vector<double> coeffArray;
241 vector<double> energyArray;
242 vector<unsigned char> occArray;
243 vector<unsigned int> numArray;
244 for (auto currentMO : moCoeffs) {
245 json coeff = currentMO.value("moCoefficients", json());
246 for (auto& j : coeff)
247 coeffArray.push_back(j);
248 if (currentMO.count("orbitalEnergy")) {
249 energyArray.push_back(currentMO["orbitalEnergy"].value("value", 0.0));
250 }
251 if (currentMO.count("orbitalOccupancy")) {
252 occArray.push_back(
253 static_cast<unsigned char>(currentMO["orbitalOccupancy"]));
254 }
255 if (currentMO.count("orbitalNumber")) {
256 numArray.push_back(
257 static_cast<unsigned int>(currentMO["orbitalNumber"]));
258 }
259 }
260 basis->setMolecularOrbitals(coeffArray);
261 basis->setMolecularOrbitalEnergy(energyArray);
262 basis->setMolecularOrbitalOccupancy(occArray);
263 basis->setMolecularOrbitalNumber(numArray);
264 basis->setElectronCount(numberOfElectrons);
265 basis->setFunctionalName(xcFunctional);
266 basis->setName(basisSetName);
267 basis->setTheoryName(theory);
268 molecule.setBasisSet(basis);
269 }
270
271 // Now to see if there was a vibrational frequencies calculation.
272 if (!calculationVib.is_null() && calculationVib.is_object()) {
273 json normalModes = calculationVib.value("calculationResults", json())
274 .value("normalModes", json());
275 if (!normalModes.is_null() && normalModes.is_array()) {
276 Array<double> frequencies;
277 Array<double> intensities;
278 Array<Array<Vector3>> Lx;
279 for (const auto& mode : normalModes) {
280 frequencies.push_back(
281 mode.value("normalModeFrequency", json()).value("value", 0.0));
282 intensities.push_back(mode.value("normalModeInfraRedIntensity", json())
283 .value("value", 0.0));
284 json lx = mode.value("normalModeVector", json()).value("value", json());
285 if (!lx.empty() && lx.is_array()) {
286 Array<Vector3> modeLx;
287 modeLx.resize(lx.size() / 3);
288 for (size_t k = 0; k < lx.size(); ++k)
289 modeLx[k / 3][k % 3] = lx[k];
290 Lx.push_back(modeLx);
291 }
292 }
293 molecule.setVibrationFrequencies(frequencies);
294 molecule.setVibrationIRIntensities(intensities);
295 molecule.setVibrationLx(Lx);
296 }
297 }
298
299 return true;
300 }
301
302 bool NWChemJson::write(std::ostream&, const Molecule&)
303 {
304 return false;
305 }
306
307 vector<std::string> NWChemJson::fileExtensions() const
308 {
309 vector<std::string> ext;
310 ext.emplace_back("nwjson");
311 return ext;
312 }
313
314 vector<std::string> NWChemJson::mimeTypes() const
315 {
316 vector<std::string> mime;
317 mime.emplace_back("chemical/x-nwjson");
318 return mime;
319 }
320
321 } // namespace Avogadro::QuantumIO